目录
五、@ResponseBody和ResponseEntity的使用
一. HttpMessageConverter<T>接口
1.HttpMessageConverter<T>是Spring3.0新添加的一个接口,负责将请求信息转换为一个对象(类型为 T),将对象输出为响应信息
2. boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);
指定转换器可以读取的对象类型。
3.boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);
指定转换器是否可将 clazz 类型的对象写到响应流中,响应流支持的媒体类型在MediaType 中定义。
4. List<MediaType> getSupportedMediaTypes();
获取该转换器支持的媒体类型。
5.T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException;
将请求信息流转换为 T 类型的对象。
6. void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;
将T类型的对象写到响应流中,同时指定相应的媒体类型为 contentType。
二、运行原理
三、如何使用HttpMessageConverter
1. 使用 HttpMessageConverter<T> 将请求信息转化并绑定到处理方法的入参中或将响应结果转为对应类型的响应信息,Spring 提供了两种途径
使用 @RequestBody / @ResponseBody 对处理方法进行标注。
使用 HttpEntity<T> / ResponseEntity<T> 作为处理方法的入参或返回值
2.当控制器处理方法使用到 @RequestBody/@ResponseBody 或HttpEntity<T> / ResponseEntity<T> 时,Spring 首先根据请求头或响应头的 Accept 属性选择匹配的 HttpMessageConverter, 进而根据参数类型或泛型类型的过滤得到匹配的 HttpMessageConverter, 若找不到可用的 HttpMessageConverter 将报错。
3.@RequestBody 和 @ResponseBody 不需要成对出现
四、@RequestBody和HttpEntity<T>的使用
需求:将请求体转换为字符串
1. 使用@RequestBody注解
- 表单页面
<h1>测试@RequsetBody注解和HttpEntity对象</h1> |
2.处理器方法
@RequestMapping(value = "/testRequestBody",method = RequestMethod.POST) |
2.同样的表单使用HttpEntity<T>
@RequestMapping(value = "/testHttpEntity",method = RequestMethod.POST) |
五、@ResponseBody和ResponseEntity<T>的使用
1. @ResponseBody注解
- 可以添加到类上也可以添加到方法上
- 添加了该注解的处理器方法方法的返回值将通过HttpMessageConverter直接响应给浏览器
- 测试案例:将字符串直接响应给浏览器
@ResponseBody |
2. 使用ResponseEntity<T>实现文件下载
1.页面连接
<a th:href="@{/testResponseEntity}">点我有惊喜!!!</a><br> |
2. 处理器方法
@RequestMapping(value = "/testResponseEntity")
|