问题
If a request is sent to my API without an Accept header, I want to make JSON the default format. I have two methods in my controller, one for XML and one for JSON:
@RequestMapping(method = RequestMethod.GET,produces=MediaType.APPLICATION_ATOM_XML_VALUE)
@ResponseBody
public ResponseEntity<SearchResultResource> getXmlData(final HttpServletRequest request) {
//get data, set XML content type in header.
}
@RequestMapping(method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Feed> getJsonData(final HttpServletRequest request){
//get data, set JSON content type in header.
}
When I send a request without an Accept header the getXmlData
method is called, which is not what I want. Is there a way to tell Spring MVC to call the getJsonData
method if no Accept header has been provided?
EDIT:
There is a defaultContentType
field in the ContentNegotiationManagerFactoryBean
that does the trick.
回答1:
From the Spring documentation, you can do this with Java config like this:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
}
If you are using Spring 5.0 or later, implement WebMvcConfigurer
instead of extending WebMvcConfigurerAdapter
. WebMvcConfigurerAdapter
has been deprecated since WebMvcConfigurer
has default methods (made possible by Java 8) and can be implemented directly without the need for an adapter.
回答2:
If you use spring 3.2.x, just add this to spring-mvc.xml
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false"/>
<property name="mediaTypes">
<value>
json=application/json
xml=application/xml
</value>
</property>
<property name="defaultContentType" value="application/json"/>
</bean>
来源:https://stackoverflow.com/questions/18189245/how-to-set-the-default-content-type-in-spring-mvc-in-no-accept-header-is-provide