3.13 @RequestBody注解 3.13.1 HttpMessageConverter接口
3.13 @RequestBody注解
用途:处理JSON、XML等数据
org.springframework.web.bind.annotation.RequestBody注解常用来处理ContentType不是application/x-ww-form-urlencoded编码的内容,例如application/json,application/xml等。
使用HttpMessageConverters类解析JSON、XML
@RequestBody注解通过使用HandlerAdapter配置的HttpMessageConverters来解析JSON或xml数据,然后绑定到相应的Bean上。
3.13.1 HttpMessageConverter接口
用途
HttpMessageConverter<T>是Spring3.0之后新增的一个重要接口,它负责将请求信息转换为一个对象(类型为T),并将对象(类型为T)绑定到请求方法的参数上或输出为响应信息。
由RequestMappingHandlerAdapter使用
DispatcherServlet默认已经装配了RequestMappingHandlerAdapter作为HandlerAdapter组件的实现类,即:HttpMessageConverter由RequestMappingHandlerAdapter使用,将请求信息转换为对象,或将对象转换为响应信息。
HttpMessageConverter接口方法
HttpMessageConverter<T>接口中定义了以下几个方法
| 方法 | 描述 |
|---|---|
boolean canRead(Class<?>clazz,MediaType mediaType) |
该方法指定转换器可以读取的对象类型, 即转换器可将请求信息转换为 clazz类型的对象,同时指定支持的 MIME类型(text/html、application/json等)。MIME媒体类型在RFC2616中定义,具体请参考 http://tools.ietf.org/html/rfc2616#section-3.7上的说明。 |
boolean canWrite(Class<?>clazz,MediaType mediaType) |
该方法指定转换器可以将clazz类型的对象写到响应流当中,响应流支持的媒体类型在 mediaType中定义。 |
List<MediaType> getSupportedMediaTypes() |
该方法返回当前转换器支持的媒体类型。 |
T read(Class<?extendsT> clazz,HttpInputMessage inputMessage) |
该方法将请求信息流转换为T类型的对象 |
void write(T t,MediaType contentType,HttpOutputMessage outputMessage) |
该方法将T类型的对象写到响应流当中,同时指定响应的媒体类型为contentType。 |
Spring提供的HttpMessageConverter接口实现类
Spring为HttpMessageConverter<T>提供了多个实现类,这些实现类组成了一个功能强大、用途广泛的信息转换家族。详细说明如下:
| 实现类 | 描述 |
|---|---|
StringHttpMessageConverter |
|
FormHttpMessageConverter |
|
SourceHttpMessageConverter |
如果部分表单属性是XML数据,则可用该转换器进行转换。 |
ResourceHttpMessageConverter |
|
BufferedImageHttpMessageConverter |
|
ByteArrayHttpMessageConverter |
|
SourceHttpMessageConverter |
|
MarshallingHttpMessageConverter |
|
Jaxb2RootElementHttpMessageConverter |
|
MappingJackson2HttpMessageConverter |
|
RssChannelHttpMessageConverter |
|
AtomFeedHttpMessageConverter |
|
默认装配的HandlerAdapter实现类
DispatcherServlet默认已经装配了RequestMappingHandlerAdapter作为HandlerAdapter组件的实现类;RequestMappingHandlerAdapter默认已经装配了以下的HttpMessageConverter:
StringHttpMessageConverterByteArrayHttpMessageConverterSourceHttpMessageConverter
自定义RequestMappingHandlerAdapter
如果需要装配其他类型的HttpMessageConverter,则可以在Spring的Web容器的上下文中自定义一个RequestMappingHandlerAdapter,如下所示:
1 | <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> |
自定义后默认装配的HttpMessageConverter
提示如果在Spring Web容器中显式定义了一个RequestMappingHandlerAdapter,则Spring MVC的RequestMappingHandlerAdapter默认装配的HttpMessageConverter将不再起作用。