具有数据绑定的AngularJS Spring MVC重定向

时间:2016-03-03 04:24:58

标签: angularjs spring spring-mvc

我是AngularJS的新手,问题可能不是很聪明。

我正在尝试使用Spring Controller中的数据绑定重定向到新页面。

我的要求是当我点击页面上的按钮/超链接(比如第1页)时,我的Spring Controller会执行业务并确定要显示的页面(第2页或第3页)。重定向页面中的数据在使用查询参数重定向期间从Spring Controller填充。

我的问题是页面重定向得很好。但是我无法在AngularJS中检索查询参数,尽管我可以在浏览器中重定向请求URL中查看它们(Google开发人员工具)。

我只添加了相关代码:

从第一个jsp页面调用的控制器方法(比如page1.jsp)重定向到page2(pageToRedirectTo.jsp)

在page1.jsp中,有一个按钮可以调用页面重定向的方法以及表单对象。

<button ng-click="ctrl.onClickOfPage1ButtonRedirect ()">Page Redirect</button> 

app.js

var angularApp = angular.module('angularApp',[]);

AngularJs控制器

this.onClickOfPage1ButtonRedirect = function(){

        Page1Service.redirectToNewPage()
        .then(
                function(d) {
                    $scope.myVal = d;
                    var e1 = angular.element(document.getElementById("dir"));
                   e1.html(d);
                   $compile(e1.contents())($scope);

               },
                function(errResponse){
                     console.error('Error.');
                } 
    );


    };

向Spring Controller发送请求的AngularJS服务

Page1Service.js

angularApp.factory('Page1Service', ['$http', '$q', function($http, $q){

    return {
 redirectToNewPage: function() {
                    return $http.post('/requestMappingUrlFromPage1')
                            .then(
                                    function(response){
                                        return response.data;
                                    }, 
                                    function(errResponse){

                                        return $q.reject(errResponse);
                                    }
                            );
            }

 };

}]);

Spring Controller

@RequestMapping(value="/requestMappingUrlFromPage1", method = RequestMethod.POST)
    public ResponseEntity<Void> redirectToNewPage(){

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

        List<ResponseDTO> responseDTO = new ArrayList<ResponseDTO>();
        //Business logic to populate responseDTO list ....



          String responseJson=  new Gson().toJson(responseDTO);
         UriComponentsBuilder b = UriComponentsBuilder.fromPath("/pageToRedirectTo");
                 UriComponents uriComponents =  b.queryParam("responseDTOList", responseJson).build();

         return new ResponseEntity<Void>(headers,HttpStatus.FOUND);

    }

现在,当我在Page1Service.js中获得响应时,它会将response.data显示为被重定向到的页面的html内容。在Google Chrome开发人员工具中,我可以看到查询参数:

responseDTOList:[{"parameter1":"123","parameter2":"Name","parameter3":false,"parameter4":false},{"parameter1":"123123","parameter2":"Name1","parameter3":false,"parameter4":false}]

在Page1Service.js

中收到回复
Object {data: "<!DOCTYPE html>
↵<html ng-app="angularApp">
↵<head>
.......
↵</body>
↵
↵</html>", status: 200, config: Object, statusText: "OK"}

有没有办法检索这些数据?

我尝试过使用$ route.params,但未定义。另外,我没有使用ng-route。使用$ location也没有用,因为我的所有页面都动态嵌入主页的自定义目录标记中,因此$ location.absUrl()始终提供主页网址。

非常感谢任何建议。非常感谢提前!!

我添加了浏览器标题参数,它在我的查询参数中显示了响应对象。但是,Angular response.data只显示HTML内容,我无法检索查询参数。

链接以查看浏览器标题:browser headers

3 个答案:

答案 0 :(得分:0)

在检查问题后,我的想法是,实现目标的一种方法是将angularJS页面转换为Thymeleaf页面。转换它非常简单,您的所有angularJS代码将保持不变。有关此目的,请参阅Thymeleaf doc。

然后你就可以像这样在js脚本中获取params

<script th:inline="javascript">
  /*<![CDATA[*/

    var message = [[${message}]];
    console.log(message);

  /*]]>*/
</script>

Javascript中获得参与后,您可以轻松进入angularJS控制器。

答案 1 :(得分:0)

如果您将Page1Service.js response.data作为HTML获取,则可以使用JSON.parse来解析内容并获取数据。 如果你更明确地提供ans会很有帮助“当我在Page1Service.js中得到响应时,它会将response.data显示为被重定向到的页面的html内容。”

答案 2 :(得分:0)

我不确定是否可以从AngularJS中的查询参数中检索响应数据。

但是,我通过在Spring Controller中重定向页面的GET请求中检索查询参数来解决我的问题。然后,我通过HttpServletResponse标头将它发送回Angular Service并在AngularJS中将其检索回来。

可能不是理想的解决方案,但这是我能在短时间内找到的解决方案,而不会对我的代码进行重大调整。

Spring Controller用于从page1重定向到page2

@RequestMapping(value="/requestMappingUrlFromPage1", method = RequestMethod.POST)
public ResponseEntity<Void> redirectToNewPage(){

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    List<ResponseDTO> responseDTO = new ArrayList<ResponseDTO>();
    //Business logic to populate responseDTO list ....



      String responseJson=  new Gson().toJson(responseDTO);
     UriComponentsBuilder b = UriComponentsBuilder.fromPath("/pageToRedirectTo");
             UriComponents uriComponents =  b.queryParam("responseDTOList", responseJson).build();

     return new ResponseEntity<Void>(headers,HttpStatus.FOUND);

}

重定向页面控制器映射

 @RequestMapping(value="/pageToRedirectTo",method = RequestMethod.GET)
     public String getpageToRedirectTo(@RequestParam(required=false, name="responseDTOList")String temp, HttpServletRequest request,HttpServletResponse response) {


        try{
        if(temp!=null){ 
             ObjectMapper mapper = new ObjectMapper();
             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
             //JSON from String to Object
             List<ResponseDTO> objList = mapper.readValue(temp,TypeFactory.defaultInstance().constructCollectionType(List.class,ResponseDTO.class));


             if(objList!=null){

                String jsonList = new Gson().toJson(objList);
                 response.setHeader("responseDTOList", jsonList);
             }

        }
        }catch(JsonMappingException jme){
            logger.error("JsonMappingException : ", jme);
        }catch(JsonParseException jpe){
            logger.error("JsonParseException : ", jpe);
        }
        catch(IOException ioe){
            logger.error("IOException : ", ioe);
        }catch(Exception e){

            logger.error("Error : ", e);

        }


         return "pageToRedirectTo";
     }

Page1Service.js

angularApp.factory('Page1Service', ['$http', '$q', function($http, $q){
return {
    redirectToNewPage: function() {
                return $http.post('/requestMappingUrlFromPage1')
                        .then(
                                function(response){
                                   var customResponse = {};

                                customResponse.responseDTOList= response.headers('responseDTOList'); 
                                customResponse.pageData = response.data;
                                return customResponse;
                                }, 
                                function(errResponse){

                                    return $q.reject(errResponse);
                                }
                        );
        }};}]);

AngularJS控制器

this.onClickOfPage1ButtonRedirect = function(){
    Page1Service.redirectToNewPage()
    .then(
            function(d) {
                $scope.responseList = d.responseDTOList;
                $scope.myVal = d.pageData;
                var e1 = angular.element(document.getElementById("dir"));
               e1.html(d);
               $compile(e1.contents())($scope);

           },
            function(errResponse){
                 console.error('Error.');
            } 
);


};