Content Negotiation Configuration
In this section, you will learn about configuring content negotiation in Spring MVC.
Content negotiation, introduced in Spring 3.2, resolves the requested media type of the request from the client. Afterward, the response is sent back to the client in the resolved media type.
The available options for determining the requested media type are :
- By checking file extension for each type of URI. For example:
http://www,roseindia.net/java/tutorial_beginner.pdf requesting PDF
representation and http://www,roseindia.net/java/tutorial_beginner.xml
requesting XML representation.
- By checking Accept HTTP request header . For example, a request for
http://www.roseindia.net/java/tutorial_beginner with an Accept header
set to 'application/pdf' requests a PDF representation.
By default, extension of the file in the request URI is checked first and "Accept" header is checked next.
You can configure the content negotiation options by the MVC Java config as shown below :
@Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.setFavorPathExtension(false).setFavorParameter(true); } }
You can configure the content negotiation options by the MVC XML Namespace as shown below :
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" /> <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <property name="favorPathExtension" value="false" /> <property name="favorParameter" value="true" /> <property name="mediaTypes" > <value> json=application/json xml=application/xml </value> </property> </bean>
In the above configuration, the element <mvc:annotation-driven> has a attribute content-negotiation-manager that accepts a ContentNegotiationManager which can be created with a ContentNegotiationManagerFactoryBean.