11.SpringMVC之HttpMessageConverter
HttpMessageConverter简介
HTTP 请求和响应的传输是字节流,意味着浏览器和服务器通过字节流进行通信。但是,使用 Spring,controller 类中的方法返回纯 String 类型或其他 Java 内建对象。如何将对象转换成字节流进行传输?
在报文到达SpringMVC和从SpringMVC出去,都存在一个字节流到java对象的转换问题。在SpringMVC中,它是由HttpMessageConverter来处理的。
当请求报文来到java中,它会被封装成为一个ServletInputStream的输入流,供我们读取报文。响应报文则是通过一个ServletOutputStream的输出流,来输出响应报文。
我们可以用下图来加深理解。

HttpMessageConverter接口
在Spring中,内置了大量的HttpMessageConverter。通过请求头信息中的MIME类型,选择相应的HttpMessageConverter。
// 数据转换器 -> 将数据转换成 requests 或 response 中的数据
public interface HttpMessageConverter<T> { // 指定的 class 是否支持读取(MediaType 指数据的格式)
boolean canRead(Class<?> clazz, MediaType mediaType); // 传入 class 与 MediaType -> 看 HttpMessageConverter 是否支持写数据到数据流中
boolean canWrite(Class<?> clazz, MediaType mediaType); // 返回 HttpMessageConverter 支持的 MediaType
List<MediaType> getSupportedMediaTypes(); // 从 HttpInputMessage 中读取数据流, 并转化成 T 这站类型
T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException; // 将 T 里面的数据信息写入到 HttpOutputMessage 的数据流中
void write(T t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;
}
HttpMessageConverter接口的定义中出现了成对的canRead(),read()和canWrite(),write()方法。MediaType是对请求的Media Type属性的封装。
read方法中有一个HttpInputMessage,我们查看它的源码如下。
public interface HttpInputMessageextends HttpMessage {
InputStreamgetBody() throws IOException;
}
HttpInputMessage提供的接口就是将body中的数据转为输入流。
write方法中有一个HttpOutputMessage,我们查看它的源码如下。
public interface HttpOutputMessageextends HttpMessage {
OutputStreamgetBody() throws IOException;
}
HttpOutputMessage提供的接口就是将body中的数据转为输出流。
它们拥有相同的父接口HttpMessage。
public interface HttpMessage {
HttpHeadersgetHeaders();
}
HttpMessage提供的方法是读取头部中的信息。
Spring中内置的一部分HttpMessageConverter
1. FormHttpMessageConverter
支持 MultiValueMap 类型, 并且 MediaType 类型是 "multipart/form-data", 从 InputStream 里面读取数据, 并通过&符号分割, 最后转换成 MultiValueMap, 或 将 MultiValueMap转换成 & 符号连接的字符串, 最后转换成字节流, 输出到远端
2. BufferedImageHttpMessageConverter
支持 BufferedImgae 的 HttpMessageConverter, 通过 ImageReader 将 HttpBody 里面的数据转换成 BufferedImage, 或ImageWriter 将ImageReader 转换成字节流输出到 OutputMessage
3. StringHttpMessageConverter
支持数据是 String 类型的, 从 InputMessage 中读取指定格式的 str, 或 将数据编码成指定的格式输出到 OutputMessage
4. SourceHttpMessageConverter
支持 DOMSource, SAXSource, StAXSource, StreamSource, Source 类型的消息转换器, 在读取的时候, 从 HttpBody 里面读取对应的数据流转换成对应对应, 输出时通过 TransformerFactory 转换成指定格式输出
5. ResourceHttpMessageConverter
支持数据类型是 Resource 的数据, 从 HttpBody 中读取数据流转换成 InputStreamResource|ByteArrayResource, 或从 Resource 中读取数据流, 输出到远端
6. ProtobufHttpMessageConverter
支持数据类型是 com.google.protobuf.Message, 通过 com.google.protobuf.Message.Builder 将 HttpBody 中的数据流转换成指定格式的 Message, 通过 ProtobufFormatter 将 com.google.protobuf.Message 转换成字节流输出到远端
7. ObjectToStringHttpMessageConverter
支持 MediaType是 text/plain 类型, 从 InputMessage 读取数据转换成字符串, 通过 ConversionService 将字符串转换成自定类型的 Object; 或将 Obj 转换成 String, 最后 将 String 转换成数据流
8. ByteArrayHttpMessageConverter
支持格式是 byte 类型, 从 InputMessage 中读取指定长度的字节流, 或将 OutputMessage 转换成字节流
9. AbstractXmlHttpMessageConverter及其子类
支持从 xml 与 Object 之间进行数据转换的 HttpMessageConverter
10. AbstractGenericHttpMessageConverter
支持从 Json 与 Object 之间进行数据转换的 HttpMessageConverter (PS: 主要通过 JackSon 或 Gson)
11. GsonHttpMessageConverter
支持 application/*++json 格式的数据, 并通过 Gson, 将字符串转换成对应的数据
12. MappingJackson2XmlHttpMessageConverter
持 application/*++json/*+xml 格式的数据, 并通过 JackSon, 将字符串转换成对应的数据
HttpMessageConverter 在整个 SpringMVC 中起着根据 MediaType 类型将 HttpServletRequest 中的数据转换成 指定对象的转换器, 或将对象转换成指定格式的数据(PS: byte/String/xml/json 等);
自定义HttpMessageConverter
1.通过继承 AbstractHttpMessageConverter自定义HttpMessageConverter
配置自定义HttpMessageConverter
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean-->
<context:component-scan base-package="com.wen.controller"/>
<!--设置默认的Servlet来响应静态文件-->
<mvc:default-servlet-handler/>
<!--设置配置方案,会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean-->
<mvc:annotation-driven>
<!--设置不使用默认的消息转换器-->
<mvc:message-converters register-defaults="false">
<!--配置Spring的转换器-->
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<!--配置fastjson中实现HttpMessageConverter接口的转换器-->
<!--FastJsonHttpMessageConverter是fastjson中实现了HttpMessageConverter接口的类-->
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!--加入支持的媒体类型:返回contentType-->
<property name="supportedMediaTypes">
<list>
<!--这里顺序一定不能写反,不然IE会出现下载提示-->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven> <!--视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/pages/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
11.SpringMVC之HttpMessageConverter的更多相关文章
- SpringMVC 中HttpMessageConverter简介和Http请求415 Unsupported Media Type的问题
一.概述: 本文介绍且记录如何解决在SpringMVC 中遇到415 Unsupported Media Type 的问题,并且顺便介绍Spring MVC的HTTP请求信息转换器HttpMessag ...
- 【SpringMVC】HttpMessageConverter报文信息转换器
HttpMessageConverter HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文 HttpMessageConverte ...
- 11. SpringMVC拦截器(资源和权限管理)
1.DispatcherServlet SpringMVC具有统一的入口DispatcherServlet,所有的请求都通过DispatcherServlet. DispatcherServl ...
- SpringMVC之HttpMessageConverter
http://blog.csdn.net/zmx729618/article/details/53034420 HttpMessageConverter接口: T read(Class<? ex ...
- 11.SpringMVC注解式开发-处理器方法的返回值
处理器方法的返回值 使用@Controller 注解的处理器的处理器方法,其返回值常用的有四种类型 1.ModelAndView 2.String 3.void 4.自定义类型对象 1.返回Model ...
- springmvc知识点整理
1.Springmvc架构 2.Springmvc组件三大组件:处理器映射器,处理器适配器,视图解析器处理器映射器:注解式处理器映射器,对类中标记了@ResquestMapping的方法进行映射,根据 ...
- 是否要学SpringMVC
如题,希望大侠们指出,不能用Spring就觉得他什么都好,本帖子意在实际工作中,对是否将Spring引入项目及如何更好的使用Spring提出启发式意见.目前已有高人表达了自己对Spring的不满,让我 ...
- 转:SpringMVC浅谈
因为项目文案需要,于是乎翻阅spring相关资料.顿觉该篇不错详尽易懂,特转载之. 转载出处: http://blog.csdn.net/gane_cheng/article/details/5278 ...
- SpringMVC的相关知识
前几天学习了SpringMVC 感觉比Servlet好用得多具体如下: 首先SpringMVC的概念: SpringMVC是一个前端控制框架,主要用来负责与页面的交互.SpringMVC是Spring ...
随机推荐
- File类与常用IO流第三章IO流概述
一:以内存为基准,按照数据的流动方向,流向内存为输入(读取数据),流出内存为输出.IO流有四大顶级父类: IO流四大顶级父类 输入流 输出流 字节流 字节输入流 InputStream 字节输出流 ...
- 认识vue-cli脚手架
ps:脚手架系列主要记录我自己(一名前端小白)对脚手架学习的一个过程,如有不对请帮忙指点一二! [抱拳] 作为一名前端开发工程师,平时开发项目大多都离不开一个重要的工具,那就是脚手架.下面让我们来了解 ...
- 【LeetCode】283.移动零
283.移动零 知识点:数组:双指针: 题目描述 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序. 示例 输入: [0,1,0,3,12] 输出: [1, ...
- Spring RestTemplate 之中文乱码
由于RestTemplate的默认构造方法初始化的StringHttpMessageConverter的默认字符集是ISO-8859-1,所以导致RestTemplate请求的响应内容会出现中文乱码. ...
- IO编程之对象序列化
对象序列化的目标是将对象保存在磁盘中或者允许在网络中直接传输对象.对象序列化机制循序把内存中的java对象转换成平台无关的二进制流,从而允许把这种二进制流持久的保存在磁盘上,通过网络将这种二进制流传输 ...
- springMVC-4-处理模型数据
返回模型数据(Model) index.jsp中 <h1>获取模型数据</h1> <a href="/model/test1">ModelAnd ...
- 注解@ConfigurationProperties使用方法(二十)
前言 最近在思考使用java config的方式进行配置,java config是指基于java配置的spring.传统的Spring一般都是基本xml配置的,后来spring3.0新增了许多java ...
- 第三十二篇 -- CreateFile、ReadFile、WriteFile
一.CreateFile 这是一个多功能的函数,可打开或创建文件或者I/O设备,并返回可访问的句柄:控制台,通信资源,目录(只读打开),磁盘驱动器,文件,邮槽,管道. 函数原型: HANDLE WIN ...
- npx的使用方法、场景
目录 npx使用教程 npm与npx的概念 npx的使用场景(对比npm的一些优势) 使用场景1: 想用项目中已经安装好的某个包, 但是不能直接执行(因为没有全局安装, 涉及环境变量的问题) 使用场景 ...
- intouch 10.1出现暂停读取PLC数据问题及其解决
问题描述 雨水泵站经过3年运行,突发dasmbtcp驱动与施耐德M580系列PLC时断时连问题 原因分析 在经过现场软件重装修复,授权重装,网络通讯状态监视(一直ping PLC IP地址方式)重装d ...