【问题标题】:How to set the default content type in Spring MVC in no Accept header is provided?如何在没有提供 Accept 标头的情况下在 Spring MVC 中设置默认内容类型?
【发布时间】:2013-08-13 21:32:37
【问题描述】:

如果发送到我的 API 的请求没有 Accept 标头,我想将 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.  
 }

当我发送没有 Accept 标头的请求时,会调用 getXmlData 方法,这不是我想要的。如果没有提供 Accept 标头,有没有办法告诉 Spring MVC 调用 getJsonData 方法?

编辑:

ContentNegotiationManagerFactoryBean 中有一个 defaultContentType 字段可以解决问题。

【问题讨论】:

  • 如果您使用ContentNegotiationManagerFactoryBean 找到了解决方案,请将其添加为解决方案。

标签: http rest spring-mvc content-negotiation


【解决方案1】:

Spring documentation,您可以像这样使用 Java 配置来做到这一点:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.defaultContentType(MediaType.APPLICATION_JSON);
  }
}

如果您使用 Spring 5.0 或更高版本,请实现 WebMvcConfigurer 而不是扩展 WebMvcConfigurerAdapterWebMvcConfigurerAdapter 已被弃用,因为 WebMvcConfigurer 具有默认方法(由 Java 8 实现)并且可以直接实现而无需适配器。

【讨论】:

  • 只是一个细节:在 Spring Boot 应用程序中,您的 @Configuration 类应该包含 @EnableWebMvc 注释 (source)。它可能会阻止其他东西工作,例如 springfox-swagger-ui html 页面。
  • WebMvcConigurerAdapter 现在已弃用,只需将extends WebMvcConfigurerAdapter 更改为implements WebMvcConfigurer
  • 因滥用 @EnableWebMvc 而被否决。 Spring Boot 不应该与它混合使用。
【解决方案2】:

如果你使用 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>

【讨论】:

  • 我把它放在我的 servlet-context.xml 中,它工作得很好。谢谢@Larry Z。
  • favorPathExtension 设置为false 时,设置mediaTypes 是否有任何影响?
  • mediaTypes 用于当喜爱参数设置为 true 时。这将检查查询参数,因此 /blahblah/4?format=xml 将解析为 application/xml。 favourParameter 的默认值为 false,因此在此示例中设置 mediaTypes 无效。
  • 嗨,在包含上述代码后,如果没有接受标头,我将默认获取 json。但如果我设置为 application/xml 。我仍然以 json 而不是 XML 的形式获得响应?我缺少什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-07
  • 1970-01-01
  • 2022-11-03
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
相关资源
最近更新 更多