目录
@RequestBody 和 @ResponseBody 两个注解,分别完成请求报文到对象和对象到响应报文的转换。
底层这种灵活的消息转换机制,就是 Spring3.x 中新引入的 HttpMessageConverter,即消息转换器机制。
而负责这种机制的主要接口HttpMessageConverter及其各种子类(StringHttpMessageConverter等),就是消息转换器。
消息转换器的结构如下图
接口说明见图:
请求处理流程见图:
这两个接口只是声明,定义一些方法。具体的实现才是最终处理。
以我们代码中的一个配置作为说明,并具体理解这个加载过程:
<mvc:annotation-driven>
<mvc:message-converters>
<ref bean="fastJsonHttpMessageConverter"/>
<ref bean="sourceHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="sourceHttpMessageConverter"
class="org.springframework.http.converter.xml.SourceHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/xml;charset=UTF-8</value>
<value>text/xml;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="fastJsonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
主要参考文章: SpringMVC关于json、xml自动转换的原理研究-附带源码分析 - format丶 - 博客园
对于注解的解析:<mvc:annotation-driven/>
。该解析由类org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser
的parse()
方法处理。
<mvc:message-converters>
属性,则加载默认的HttpMessageConverter。
如同上述配置,则只会加载两个sourceHttpMessageConverter
和fastJsonHttpMessageConverter
。
我们配置了多个HttpMessageConverter,而每个HttpMessageConverter可以处理哪些类型的请求则由supportedMediaTypes属性定义(不止该属性,但也是一部分)
这部分的具体使用在:
supportedMediaType
的过滤至此,我们可以确定,XML的配置中的supportedMediaTypes会音响该消息转换器可以处理的请求。以上述配置为例,sourceHttpMessageConverter负责处理XML数据格式的请求;fastJsonHttpMessageConverter处理json格式的请求。
canWrite方法也会用到supportedMediaTypes,可以自行梳理。至此,消息转换器的配置以及生效过程就比较清晰了。
- SpringMVC 源码剖析(五)- 消息转换器 HttpMessageConverter - 相见欢的个人空间 - OSCHINA
注:本篇博客就是该文章的翻版,所以原文很重要。- SpringMVC关于json、xml自动转换的原理研究-附带源码分析 - format丶 - 博客园
注:对配置的生效过程说明很详细,可以参考。- Spring MVC 解读—— - Don‘t worry, Loser. - OSCHINA
注:对于Spring XML配置的解析说明很清楚。重点: 标签解析都是由BeanDefinitionParser接口的子类来完成的。还有对于AnnotationDrivenBeanDefinitionParser 的详细解析。- springMVC的消息转换器(Message Converter) - 简书
注:对于自定义消息转换器说明很棒,源码说明也不错。- SpringMVC HttpMessageConverter 匹配规则 - - SegmentFault 思否
注:匹配规则,很深奥看不懂的感觉,后续再看。
原文:https://www.cnblogs.com/buwuliao/p/11859103.html