SpringMVC处理Json-使用 HttpMessageConverter

一、HttpMessageConverter  

作用:它负责将请求信息转换为一个对象(类型为T),将该对象输出为响应信息。

     其实:DispatcherServlet默认已经安装了AnnotationMethodHandlerAdapter作为HandlerAdapter组件的实现类,HttpMessageConverter即由AnnotationMethodHandlerAdapter使用,将请求信息转换为对象,或将对象转换为响应信息。


◇那么问题来了?
        问题1:如何使用HttpMessageConverter  将请求信息转化并绑定到处理方法的入参当中呢?

    解答:      
  1.使用@RequestBody/@ResponseBody对处理方法进行标注
          2.使用HttpEntity/ResponseEntity作为处理方法的入参或者返回值

                    
                    示例1:
           @RequestMapping("/handle1" )
                     public String handle1( @RequestBody String requebody) {
                          return "success" ;
                         }
                    解:将请求报文体转换为字符串绑定到reqeustBody入参中。


                    示例2:
                   @ResponseBody
                @RequestMapping"/getEmployeesForJson")
                    public  Collection getEmployees() {
                          return employeeDao .getAll();
                    }
               解:将集合数据转换为json数据并输出到响应流中。


    问题2:处理方法如何知道请求消息的格式?在处理完成后又是根据什么确定响应消息的格式嗯?

     解答:根据请求消息头的”Content-Type“及Accept属性确定。
    
      例如:
1). 分析原理

①. 请求时的目标类型:


②. 方法的实际返回值为:Employee 的集合

③. SpringMVC 发现需要返回的是 JSON 类型,但实际返回的是 Employee 的集合。此时 @ResponseBody 查找有没有把结果转为 JSON
的 HttpMessageConverter,如果有,则调用其对应的方法,把结果转为 JSON 类型。


结论:

1.只有当处理器方法使用到 @RequestBody/@ResponseBody 或HttpEntity/ResponseEntity 时,SpringMVC才使用注册的HttpMessageConverter 对 请求响应消息进行处理。

2.当控制器处理方法使用到 @RequestBody/@ResponseBody 或HttpEntity/ResponseEntity 时,Spring 首先根据请求头或响应头的 Accept 属性选择匹配的 HttpMessageConverter, 进而根据参数类型或泛型类型的过滤得到匹配的 HttpMessageConverter, 若找不到可用的 HttpMessageConverter 将报错

3.@RequestBody 和 @ResponseBody 不需要成对出现。如果方法入参使用到了@RequestBody,SpringMVC将会选择匹配的HttpMessageConverter 将
请求信息转换并绑定到该入参中。如果处理方法标注了@ResponseBody,SpringMVC选择匹配的HttpMessageConverter 将方法返回值转换并输出 响应消息。




一、示例—文件下载:
     @RequestMapping("/testHttpMessageConverter" )
     public ResponseEntity< byte[]> testHttpMessageConverter(@RequestBody String requestBody,
              HttpSession session) throws IOException{
          System. out.println(requestBody);
          
          InputStream in = session.getServletContext().getResourceAsStream("/WEB-INF/files/abc.pdf" );
           byte [] bytes = new byte[in.available()];
          in.read(bytes);
          
          HttpHeaders headers = new HttpHeaders();
          headers.add( "Content-Disposition""attachment;filename=a.pdf" );
          
          HttpStatus statusCode = HttpStatus. OK;
          
          ResponseEntity< byte[]> re = new ResponseEntity<byte []>(bytes, headers, statusCode);
           return re;
     }



二、获取json数据示例

1.页面请求:< a href ="getEmployeesForJson" id ="json">testForJson a>

2.发post请求:
<script type"text/javascript" src="scripts/jquery-1.9.1.min.js" >script>
<script type"text/javascript">
     $(function(){
          $( "#json").click(function (){
               var url=this .href;
               var args={};
               $.post(url,args, function(data){
                   
                    for(var i=0;i
                   
                        alert( "lastName:"+data[i].lastName+",department:" +data[i].department.departmentName);
                        
                   }
              });  
               return false ;
          });
     });

script>

三、处理请求
          
  @ResponseBody
     @RequestMapping"/getEmployeesForJson")
     public  Collection getEmployees() {
           return employeeDao .getAll();
     }
     
四、配置用于处理json的HttpMessageConverter

< mvc:annotation-driven >mvc:annotation-driven


显示声明:
[html]  view plain  copy
 print ?
  1. pre>div>div><div align="left" style="font-family: Cambria; orphans: 2; widows: 2;"><span style="font-family: Corbel;"><span style="font-size:18px;">span>span><pre name="code" class="html"><mvc:annotation-driven>  
  2.           
  3.           
  4.         <mvc:message-converters register-defaults="true">  
  5.             <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">bean>  
  6.         mvc:message-converters>  
  7.     mvc:annotation-driven>   



注意:要在JRE环境中添加  jackson-all-1.9.11.jar

转自:http://blog.csdn.net/u010834071/article/details/41773371

你可能感兴趣的:(SpringMVC)