Spring 4 – ContentNegotiatingViewResolver Sample

Hello every one, recently in one of my project i had a requirement that i need to generate multiple views based on the request type, this has lead me to write this post. In this article i will be explaining about “ContentNegotiatingViewResolver” class.

ContentNegotiatingViewResolver class is a implementation of ViewResolver. The ContentNegotiatingViewResolver does not resolve the view by itself unlike the ViewResolver based on the request type or the Header type in fact this delegates the request to other ViewResolvers that are configured explicitly.

This view resolver uses the requested media type to select a suitable View for a request. The requested media type is determined through the configured ContentNegotiationManager. Once the requested media type has been determined, this resolver queries each delegate view resolver for a View and determines if the requested media type is compatible with the view’s content type). The most compatible view is returned.

Let us look into the above class little deep, First we have created ContentNegotiationManager which is used to determine the requested media types of a request by delegating to a list of ContentNegotiationStrategy instances. By default PathExtensionContentNegotiationStrategy is consulted (which uses the URL extension e.g. .xls, .pdf,.json..) , followed by ParameterContentNegotiationStrategy (which uses the request parameter ‘format=xls’ e.g.), followed by HeaderContentNegotiationStrategy (which uses HTTP Accept Headers) the ContentNegotiationManager instance is injected by Spring Container.Snippet