现在的位置: 首页 > 综合 > 正文

Spring MVC 学习笔记 九 json格式的输入和输出

2012年04月01日 ⁄ 综合 ⁄ 共 3744字 ⁄ 字号 评论关闭
Spring mvc处理json需要使用jackson的类库,因此为支持json格式的输入输出需要先修改pom.xml增加jackson包的引用 

Xml代码  收藏代码
  1. <!-- json -->  
  2. <dependency>  
  3.     <groupId>org.codehaus.jackson</groupId>  
  4.     <artifactId>jackson-core-lgpl</artifactId>  
  5.     <version>1.8.1</version>  
  6. </dependency>  
  7.   
  8. <dependency>  
  9.     <groupId>org.codehaus.jackson</groupId>  
  10.     <artifactId>jackson-mapper-lgpl</artifactId>  
  11.     <version>1.8.1</version>  
  12. </dependency>  

先修改之前的helloworld.jsp,增加客户端json格式的数据输入。 

Javascript代码  收藏代码
  1.     var cfg =   {  
  2.         type: 'POST',   
  3.         data: JSON.stringify({userName:'winzip',password:'password',mobileNO:'13818881888'}),   
  4.         dataType: 'json',  
  5.         contentType:'application/json;charset=UTF-8',         
  6.         success: function(result) {   
  7.             alert(result.success);   
  8.         }   
  9.     };  
  10.   
  11. function doTestJson(actionName){  
  12.     cfg.url = actionName;  
  13.     $.ajax(cfg);  
  14. }  

根据前面的分析,在spring mvc中解析输入为json格式的数据有两种方式 
1:使用@RequestBody来设置输入 

Java代码  收藏代码
  1.     @RequestMapping("/json1")  
  2.     @ResponseBody  
  3.     public JsonResult testJson1(@RequestBody User u){  
  4.         log.info("get json input from request body annotation");  
  5.         log.info(u.getUserName());  
  6.         return new JsonResult(true,"return ok");  
  7. }  

2:使用HttpEntity来实现输入绑定 

Java代码  收藏代码
  1.     @RequestMapping("/json2")      
  2.     public ResponseEntity<JsonResult> testJson2(HttpEntity<User> u){  
  3.         log.info("get json input from HttpEntity annotation");  
  4.         log.info(u.getBody().getUserName());  
  5.         ResponseEntity<JsonResult> responseResult = new ResponseEntity<JsonResult>( new JsonResult(true,"return ok"),HttpStatus.OK);  
  6.         return responseResult;  
  7. }  

Json格式的输出也对应有两种方式 
1:使用@responseBody来设置输出内容为context body 
2:返回值设置为ResponseEntity<?>类型,以返回context body 
另外,第三种方式是使用ContentNegotiatingViewResolver来设置输出为json格式,需要修改servlet context配置文件如下 

Xml代码  收藏代码
  1. <bean  
  2.     class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">  
  3.     <property name="order" value="1" />  
  4.     <property name="mediaTypes">  
  5.         <map>  
  6.             <entry key="json" value="application/json" />  
  7.         </map>  
  8.     </property>  
  9.     <property name="defaultViews">  
  10.         <list>  
  11.             <bean  
  12.                 class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />  
  13.         </list>  
  14.     </property>  
  15.     <property name="ignoreAcceptHeader" value="true" />  
  16. </bean>  

但这种格式的输出会返回{model类名:{内容}} 的json格式, 
例如,以下代码 

Java代码  收藏代码
  1. @RequestMapping("/json3.json")  
  2. public JsonResult testJson3(@RequestBody User u){  
  3.     log.info("handle json output from ContentNegotiatingViewResolver");  
  4.     return new JsonResult(true,"return ok");  
  5. }  

期望的返回是 {success:true,message:”return ok”}; 
但实际返回的却是 {"jsonResult":{"success":true,"msg":"return ok"}} 
原因是MappingJacksonJsonView中对返回值的处理未考虑modelMap中只有一个值的情况,直接是按照mapName:{mapResult}的格式来返回数据的。 
修改方法,重载MappingJacksonJsonView类并重写filterModel方法如下 

Java代码  收藏代码
  1. protected Object filterModel(Map<String, Object> model) {    
  2.     Map<?, ?> result = (Map<?, ?>) super.filterModel(model);    
  3.     if (result.size() == 1) {    
  4.         return result.values().iterator().next();    
  5.     } else {    
  6.         return result;    
  7.     }    
  8. }    

对应的ContentNegotiatingViewResolver修改如下 

Xml代码  收藏代码
  1. <bean  
  2.         class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">  
  3.         <property name="order" value="1" />  
  4.         <property name="mediaTypes">  
  5.             <map>  
  6.                 <entry key="json" value="application/json" />  
  7.             </map>  
  8.         </property>  
  9.         <property name="defaultViews">  
  10.             <list>  
  11.                 <bean  
  12.                     class="net.zhepu.json.MappingJacksonJsonView" />  
  13.             </list>  
  14.         </property>  
  15.         <property name="ignoreAcceptHeader" value="true" />  
  16.     </bean>  

抱歉!评论已关闭.