In Spring 3.0 the AnnotationMethodHandlerAdapter
is extended to support the @RequestBody and has the following HttpMessageConverters
registered by default:
-
ByteArrayHttpMessageConverter
converts byte arrays. StringHttpMessageConverter
converts strings. FormHttpMessageConverter
converts form data to/from a MultiValueMap<String,String>. SourceHttpMessageConverter
converts to/from a javax.xml.transform.Source. MarshallingHttpMessageConverter
converts to/from an object using the org.springframework.oxm
package.
In-order to support JavaScript Object Notation - JSON response, you will need to create an AnnotationMethodHandlerAdapter
bean in your spring configuration with a MappingJacksonHttpMessageConverter
and annotate your Controller service method with the @RequestBody
annotation.
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="order" value="1" />
<property name="messageConverters">
<list>
<!-- Message converters -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
The above configuration instruct Spring to iterate over message converters sequentially until it find one that matches the object you are returning.
Listing 1.
@Controller
public class MovieController {
@RequestMapping(value="/movie/{id}", method=RequestMethod.GET)
@ResponseBody
public Movie getMovie(@PathVariable Integer id)
{
return MovieService.findMovie(id);
}
}
In the listing 1 example above, the getMovie
method returns a Movie
object, Spring iterate through the message converters in the AnnotationMethodHandlerAdapter
list for a suitable message converter and because Movie
class is not handled by others, it fall back to MappingJacksonHttpMessageConverter
hence returned as JSON.