SpringMVC处理Json-使用 HttpMessageConverter

一、HttpMessageConverter<T>  

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

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


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

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

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


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


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

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

①. 请求时的目标类型:


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

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


结论:

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

2.当控制器处理方法使用到 @RequestBody/@ResponseBody 或HttpEntity<T>/ResponseEntity<T> 时,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<data.length;i++){
                   
                        alert( "lastName:"+data[i].lastName+",department:" +data[i].department.departmentName);
                        
                   }
              });  
               return false ;
          });
     });

</script>

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

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


显示声明:
</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>
		
		<!-- 注册处理 JSON 的转换器 -->
		<mvc:message-converters register-defaults="true">
			<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
		</mvc:message-converters>
	</mvc:annotation-driven> 



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


----欢迎各位技术宅批评指正!---


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值