use*_*834 26 rest http spring-mvc content-negotiation
如果在没有Accept标头的情况下将请求发送到我的API,我想将JSON设置为默认格式.我的控制器中有两个方法,一个用于XML,另一个用于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.
}
Run Code Online (Sandbox Code Playgroud)
当我发送没有Accept标头的请求时,getXmlData会调用该方法,这不是我想要的.getJsonData如果没有提供Accept标头,有没有办法告诉Spring MVC调用该方法?
编辑:
有一个defaultContentType领域ContentNegotiationManagerFactoryBean可以解决问题.
Rus*_*bot 27
从Spring文档中,您可以使用Java配置执行此操作,如下所示:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Spring 5.0或更高版本,请使用WebMvcConfigurer而不是WebMvcConfigurerAdapter.WebMvcConfigurerAdapter由于默认方法而被弃用WebMvcConfigurer.
Lar*_*y.Z 12
如果使用spring 3.2.x,只需将其添加到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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28897 次 |
| 最近记录: |