springMVC傳對象參數、返回JSON格式數據


假如請求路徑:http://localhost/test/test.do?user.id=1

后台接收參數的方法如下:

 

        @RequestMapping("/test")  
        public ModelAndView test(HttpServletRequest request,HttpServletResponse response,User user) throws IOException {  
            response.setContentType("text/html; charset=utf-8");  
            PrintWriter out = response.getWriter();  
            System.out.println("user.id=" + user.getId());  
              
            JSONObject jsonObject=new JSONObject();  
              
            JSONObject userJson=new JSONObject();  
            userJson.put("id", user.getId());  
            userJson.put("name", "張三");  
              
              
            jsonObject.put("user", userJson);  
              
            out.print(jsonObject.toString());  
            return null;//這里需return null,如果return new ModelAndView則會直接轉發   
        }  

 

那么在后台接收到的參數中,user對象的id屬性是null。如果路徑換為http://localhost/test/test.do?id=1,則user對象的id屬性是1。

這里必須用id=1而不是user.id=1,因為默認情況下springMVC是不支持user.id這種傳參方式的。

要想springMVC支持user.id這種傳參方式,需要在controller中添加一個前綴綁定:

    @InitBinder("user")  
    public void initBinderByUser(WebDataBinder binder) {  
        binder.setFieldDefaultPrefix("user.");  
    }  

如果接收到的參數不止一個對象,比如有user、admin,則添加相應的前綴綁定:

    @InitBinder("user")  
        public void initBinderByUser(WebDataBinder binder) {  
            binder.setFieldDefaultPrefix("user.");  
        }  
          
        @InitBinder("admin")  
        public void initBinderByAdmin(WebDataBinder binder) {  
            binder.setFieldDefaultPrefix("admin.");  
        }  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM