Quick note about spring mvc http message converter. Especially thanks to this post by Eugen Paraschiv.
Http Message Converters
An example:
-
Client sends a GET request to /foos with two headers
Accept: application/json
andContent-type: application/xml
. To tell server that the request body is in xml and we want the server to return json. -
Spring controller is hit. With
@RequestBody
annotation andContent-type
of client, the request body will be converted from xml to specified java entity as argument of method by xml converter. -
When spring controller returns a response. With
@ResponseBody
annotation andAccept
of client, the return value/object will be converted from specified java entity to json by json converter.
Converters Type
By default, the following HttpMessageConverters instances are pre-enabled:
- StringHttpMessageConverter – converts Strings
- MappingJackson2HttpMessageConverter – converts to/from JSON
- Jaxb2RootElementHttpMessageConverter – converts to/from XML
- For the other converters - Message Converters
Set Up
We must declare explicitly support for annotation-driven MVC controllers
We could also use @EnableWebMvc
annotation to do the same thing.
@RequestBody
@RequestBody
indicates that the body of the HTTP Request is deserialized to that particular Java entity as method argument.
Content-Type
header specified by the Client will be used to determine the appropriate converter for it. So Content-Type: application/xml
here to choose a xml converter which will convert xml content in request body to User object in method argument.
@ResponseBody
@ResponseBody
indicates that the return value of the method is serialized directly to the body of the HTTP Response.
Accept
header specified by the Client will be used to choose the appropriate Http Converter to marshall the entity. So Accept: application/json
here to choose a json converter which will convert user object to json fromat in the http response body.