There are two ways to generate output using Spring MVC:
- You can use the RESTful
@ResponseBody
approach and HTTP message converters, typically to return data-formats like JSON or XML. Programmatic clients, mobile apps and AJAX enabled browsers are the usual clients.
- Alternatively you may use view resolution. Although views are perfectly capable of generating JSON and XML if you wish (more on that in my next post), views are normally used to generate presentation formats like HTML for a traditional web-application.
- Actually there is a third possibility - some applications require both, and Spring MVC supports such combinations easily. We will come back to that right at the end.
In either case you'll need to deal with multiple representations (or views) of the same data returned by the controller. Working out which data format to return is called Content Negotiation.
There are three situations where we need to know what type of data-format to send in the HTTP response:
- HttpMessageConverters: Determine the right converter to use.
- Request Mappings: Map an incoming HTTP request to different methods that return different formats.
- View Resolution: Pick the right view to use.
Determining what format the user has requested relies on a ContentNegotationStrategy
. There are default implementations available out of the box, but you can also implement your own if you wish.
In this post I want to discuss how to configure and use content negotiation with Spring, mostly in terms of RESTful Controllers using HTTP message converters. In a later post I will show how to setup content negotiation specifically for use with views using Spring's ContentNegotiatingViewResolver
…