Determining the Requested Media Type in Spring MVC
by, 11-28-2011 at 01:12 AM (2209 Views)
In my previous tips, we looked at the components Spring uses to determine the appropriate media type for the results returned. We know that the ContentNegotiatingViewResolver is used to determine what the appropriate media type is for the results. I will discuss the first part of the strategy used for making this determination. This involves determining the requested media type(s).
When the controller’s handler method finishes, and a logical view name is usually returned. The DispatcherServlet passes the view name to a view resolver in order to facilitate the determination of which view should render the results of the request. The view resolver that is used for RESTful services is the ContentNegotiatingViewResolver. In the first step the ContentNegotiatingViewResolver will try to determine the requested media type.
It would seem straightforward for the ContentNegotiatingViewResolver to just use the request’s Accept header in order to know what representation should be sent to the client. Unfortunately, the Accept header is not always be reliable. If the client in question is a web browser, there’s no guarantee that what the client wants is what the browser sends in the Accept header. Web browsers will usually accept human- friendly content types (such as text/html) but it’s impossible to know if it will specify a different content type.
ContentNegotiatingViewResolver might use the Accept header and the media types it requests but it will do this only after interrogating the URL’s file extension. If the URL has a file extension on the end, it’ will match that extension against the entries in the mediaTypes property. The map that contains the mediaTypes has keys that are file extensions and whose values are media types. If a match is found, then the media type will be used. In this way, the file extension can override any media types in the Accept header.
So a file extension will generally override the requested media type from the Accept header. Otherwise it will use the Accept header. If there is no Accept header, it will use the default ContentType property. In the next tip, I will look at the second part of determining the appropriate media type, How other factors can influence the media type selected.