如何在没有Accept标头的Spring MVC中设置默认内容类型?

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.

  • 只是一个细节:在 Spring 启动应用程序中,你的 `@Configuration` 类应该**不**包含 `@EnableWebMvc` 注释([来源](https://dzone.com/articles/spring-boot-enablewebmvc-和-常见用例))。它可能会阻止其他工作,例如 springfox-swagger-ui html 页面。 (2认同)
  • 现在已弃用“ WebMvcConigurerAdapter”,只需更改“将WebMvcConfigurerAdapter扩展为实现WebMvcConfigurer”即可。 (2认同)

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)

  • 当favorParameter设置为true时使用mediaTypes。这将检查查询参数,因此 /blahblah/4?format=xml 将解析为 application/xml。favorParameter 的默认值为 false,因此在此示例中设置 mediaTypes 无效。 (2认同)
  • 你好,包含上面的代码后,如果没有接受标头,我将默认获取 json 。但如果我设置为 application/xml 。我仍然得到 json 格式的响应而不是 XML?我缺少什么? (2认同)