Monday, 8 October 2012

JSON in Spring as @RequestBody of a Form Controller

This post explains how to render JSON objects in the Spring MVC in a form controller class while being able to pass other types of objects within the same application.

In Spring 3.x the AnnotationMethodHandlerAdapter class is extended to support the @RequestBody parameter 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 objectcs), 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.

The following snippet shows the Spring configuration required to iterate over the message converters sequentially until it finds one that matches the object you are returning, so it can render JSON objects from the form controller receiving the data:

The method shown in the next Java snippet receives a ContactUpdateList object, which is not a standard Java object; Spring will iterate through the message converters in the AnnotationMethodHandlerAdapter list for a suitable message converter and because the ContactUpdateList class is not handled by any of the other converters, it will eventually get to the MappingJacksonHttpMessageConverter, hence the object will be handled as a JSON.


This post could perfectly finish at this point if you were only interested in processing JSON objects of the same type, but if that is not the case and your Spring application needs to use other types of converters keep reading.

By default the Spring MVC defines three different request handler adapters, they are:
  • org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter
  • org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter
  • org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
So you do not need to define them in your context file. However, if you define at least one handler adapter in your context files, Spring will ignore the default adapters and will not create them.

Since we are creating the AnnotationMethodHandlerAdapter in our example context definition above, Spring will not create the other two handler adapters.


In case you need to use other types of adapters, you will have to specifically create the beans for those adapters, as shown next:


No comments:

Post a Comment