Finding the Appropriate View in Spring
by, 11-28-2011 at 02:19 AM (1259 Views)
In my previous tips we have gone through calling the appropriate RESTful methods, returning the results, and the initial parts of the determining the view involving determining the appropriate media type and looked at factors that could influence that decision. In the last tip on RESTful services I will show how the appropriate view is selected.
Given that our previous post focused on the ContentNegotiatingViewResolver, one would expect that this view resolver directly resolves the views. In fact it doesnít. Instead, it delegates this responsibility to other view resolvers to find a view that best suits the client. Unless otherwise specified, itíll use any view resolver in the application context. You still have the ability to explicitly list the view resolvers it should delegate to by setting the viewResolvers property.
The ContentNegotiatingViewResolver will ask all of its view resolvers to resolve the logical view name into a view. Every view thatís resolved is added to a list of candidate views. In addition, if a view is specified in the defaultView property, itíll be added to the end of the candidate view list.
With the candidate view list assembled, the ContentNegotiatingViewResolver cycles through all of the requested media types, searching for a view among the candidates that produces the matching content type. It resolve this on a first come first served basis. The first match that is found will be used with the content.
In the case that the ContentNegotiatingViewResolver doesnít find a suitable view, it returns a null view. Or, if useNotAcceptableStatusCode is set to true, then a view with an HTTP status code of 406 (Not Acceptable) will be returned.
If you are developing RESTful services that a consumed by a machine, it would be wise to develop a controller that acknowledges that the resource will be consumed by an application. If you are interested in doing this, I recommend that you look at Springís documentation on itís HTTP message converters and the @ResponseBody annotation. Thatís it for now.