2016-03-03 95 views
0

我是AngularJS的新手,这个问题可能不是很聪明。AngularJS Spring MVC重定向与数据绑定

我试图重定向到一个新的页面与Spring Controller的数据绑定。我的要求是,当我点击页面上的按钮/超链接(比如页面1)时,我的Spring控制器执行业务并确定要显示哪个页面(页面2或页面3)。重定向页面中的数据在重定向期间使用查询参数从Spring Controller填充。

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

我只添加了相关代码:

控制器的方法从第一jsp页面调用(说的Page1.jsp)重定向到第2页(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.'); 
       } 
    ); 


    }; 

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); 
            } 
          ); 
      } 

}; 

}]); 

春季控制器

@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内容被重定向到。在谷歌C​​hrome开发者工具,我可以看到的查询参数:在Page1Service.js

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

收到

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

反应是有办法找回这些数据?

我已经尝试使用$ route.params,但它是未定义的。另外,我没有使用ng-route。使用$ location也没有用,因为我的所有页面都被动态地嵌入到主页的自定义dir标签中,所以$ location.absUrl()总是给出主页的url。

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

我已经添加了浏览器头部参数,它显示了我的查询参数中的响应对象。然而,Angular response.data仅显示HTML内容,而我无法检索查询参数。

链接打开浏览器标题:browser headers

回答

0

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

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

可能不是理想的解决方案,但这是我可以在短时间内找到的解决方案,无需对代码进行重大重构。

弹簧控制器,用于从第1页重定向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.'); 
      } 
); 


}; 
0

其流行在我的脑海检查后,您的问题是,实现自己的目标的方法之一是angularJS页面转换成Thymeleaf页的想法。它非常简单的转换它,你的代码将保持不变。请参阅Thymeleaf doc以达到此目的。

然后,只需你可以在JS脚本PARAMS这样

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

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

    /*]]>*/ 
</script> 

一旦你得到了在Javascript您的PARMS那么你可以很容易地进入angularJS控制器。

+0

感谢您的建议Muhammad Suleman,但由于项目需求限制,我无法从angularJS更改为Thymeleaf。 – Vidisha

+0

但我想Thymeleaf页面对所有angularJS页面同样有效。它对他们无害。其实我面临类似的问题,这是解决方法。当然,选择是你的。 –

0

如果您将Page1Service.js response.data作为HTML获取,则可以使用JSON.parse来解析内容并获取数据。 如果您在“Page1Service.js”中获得响应时进行更加清晰的提供,将会对您有所帮助,它会将页面的html内容显示为response.data,并将其重定向到

+0

我已经添加的响应,我接收在response.data在Page1Service.js 对象{数据: “ .... ↵HTML纳克应用内=><!DOCTYPE HTML!>“ ... ↵ ↵ ↵”,状态:200,配置:对象,状态文本: “OK”} 我还添加了链接到的图像显示在浏览器标题参数。 – Vidisha