SpringMVC 学习笔记(七) JSON返回:HttpMessageConverter作用

版权声明:本文为博主原创文章,博客地址:http://blog.csdn.net/a67474506?viewmode=contents

目录(?)[+]

 

1.1. 返回JSON

在POM.XML:

[html] view plain copy

  1. <dependency>  
  2.             <groupId>com.fasterxml.jackson.core</groupId>  
  3.             <artifactId>jackson-databind</artifactId>  
  4.             <version>2.1.4</version>  
  5.         </dependency>  

 

在方法上面添加@ResponseBody注解

 

 

1.2. HttpMessageConverter

HttpMessageConverter<T> 是 Spring3.0 新添加的一个接口,负责将请求信息转换为一个对象(类型为 T),将对象(类型为 T)输出为响应信息

[java] view plain copy

  1. public interface HttpMessageConverter<T> {  
  2.   
  3.     /** 
  4.      * 指定转换器可以读取的对象类型, 
  5.      * 即转换器是否可将请求信息转换为 clazz 类型的对象, 
  6.      * 同时指定支持 MIME 类型(text/html,applaiction/json等) 
  7.      */  
  8.     boolean canRead(Class<?> clazz, MediaType mediaType);  
  9.   
  10.     /** 
  11.      * 指定转换器是否可将 clazz 类型的对象写到响应流中, 
  12.      * 响应流支持的媒体类型 
  13.      * 在MediaType 中定义。 
  14.      */  
  15.     boolean canWrite(Class<?> clazz, MediaType mediaType);  
  16.   
  17.     /** 
  18.      * 该转换器支持的媒体类型。   
  19.      */  
  20.     List<MediaType> getSupportedMediaTypes();  
  21.   
  22.     /** 
  23.      * 将请求信息流转换为 T 类型的对象。 
  24.      */  
  25.     T read(Class<? extends T> clazz, HttpInputMessage inputMessage)  
  26.             throws IOException, HttpMessageNotReadableException;  
  27.   
  28.     /** 
  29.      * 将T类型的对象写到响应流中,同时指定相应的媒体类型为 contentType 
  30.      */  
  31.     void write(T t, MediaType contentType, HttpOutputMessage outputMessage)  
  32.             throws IOException, HttpMessageNotWritableException;  
  33.   
  34. }  

 

1.2.1. HttpMessageConverter<T> 的实现类

 

 

1.2.2. 处理流程

 

 

 

 

DispatcherServlet 默认装配RequestMappingHandlerAdapter 

RequestMappingHandlerAdapter 默认装配如下HttpMessageConverter

 

 

当加入jsckson 包后,RequestMappingHandlerAdapter装配的 HttpMessageConverter 如下:

 

 

使用 HttpMessageConverter<T> 将请求信息转化并绑定到处理方法的入参中或将响应结果转为对应类型的响应信息,Spring 提供了两种途径:

– 使用 @RequestBody / @ResponseBody 对处理方法进行标注

– 使用 HttpEntity<T> / ResponseEntity<T> 作为处理方法的入参或返回值

当控制器处理方法使用到@RequestBody/@ResponseBody

HttpEntity<T>/ResponseEntity<T> 时, Spring 首先根据请求头或响应头的Accept 属性选择匹配的 HttpMessageConverter, 进而根据参数类型或泛型类型的过滤得到匹配的 HttpMessageConverter, 若找不到可用的HttpMessageConverter 将报错

@RequestBody 和 @ResponseBody 不需要成对出现

 

 

 

1.2.3. @RequestBody和@ResponseBody示例

[java] view plain copy

  1. @ResponseBody  
  2. @RequestMapping("/responseBody")  
  3. public byte[] responseBody(HttpSession session) throws IOException {  
  4.     ServletContext servletContext = session.getServletContext();  
  5.     InputStream in = servletContext.getResourceAsStream("/WEB-INF/files/download.txt");  
  6.     byte[] fileData = FileCopyUtils.copyToByteArray(in);  
  7.     return fileData;  
  8. }  
  9.   
  10. @RequestMapping("/requestBody")  
  11. public String requestBody(@RequestBody String body){  
  12.     System.out.println(body);  
  13.     return "helloworld";  
  14. }  


JSP:

 

 

[html] view plain copy

  1. <form action="requestBody" method="POST" enctype="multipart/form-data">  
  2.     File: <input type="file" name="file"/>  
  3.     Desc: <input type="text" name="desc"/>  
  4.     <input type="submit" value="Submit"/>  
  5. </form>  
  6. <br>  
  7. <br>  
  8. <a href="responseBody"> responseBody </a>  
  9. <br>  
  10. <br>  

 

1.2.4. HttpEntity和ResponseEntity 示例

[html] view plain copy

  1.     @RequestMapping("/httpEntity")  
  2.     public String httpEntity(HttpEntity<String> entity){  
  3.         System.out.println(entity.getHeaders().getContentLength());  
  4.         return "helloworld";  
  5.     }  
  6.       
  7.     @RequestMapping("/download")  
  8.     public ResponseEntity<byte[]> responseEntity(HttpSession session) throws IOException{  
  9.         byte [] body = null;  
  10.         ServletContext servletContext = session.getServletContext();  
  11.         InputStream in = servletContext.getResourceAsStream("/WEB-INF/files/download.txt");  
  12.         body = new byte[in.available()];  
  13.         in.read(body);  
  14.           
  15.         HttpHeaders headers = new HttpHeaders();  
  16.         headers.add("Content-Disposition", "attachment;filename=download.txt");  
  17.           
  18.         HttpStatus statusCode = HttpStatus.OK;  
  19.           
  20.         ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);  
  21.         return response;  
  22.     }  
  23. JSP:  
  24. <br>  
  25. <a href="download"> download </a>  
  26. <br>  
  27. <br>  
  28. <a href="httpEntity"> httpEntity </a>  
  29. <br>  
  30. <br>  
  31.  

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值