如果没有提供Accept头,如何在Spring MVC中设置默认内容类型?

30
如果API接收到一个没有Accept头的请求,我希望将JSON设置为默认格式。我的控制器中有两种方法,一种是XML,另一种是JSON:
如果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 header的请求时,会调用getXmlData方法,这不是我想要的。有没有办法告诉Spring MVC,在没有提供Accept header的情况下调用getJsonData方法?
编辑:在ContentNegotiationManagerFactoryBean中有一个defaultContentType字段可以解决这个问题。

3
如果您使用了ContentNegotiationManagerFactoryBean找到了解决方案,请将其添加为解决方案。 - Vijay Kukkala
2个回答

38

根据Spring文档,你可以使用Java配置来实现这一点:

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

若您使用的是Spring 5.0或之后的版本,请实现WebMvcConfigurer而不是继承WebMvcConfigurerAdapter。由于WebMvcConfigurer支持默认方法(这在Java 8中成为可能),并且可以直接实现,因此WebMvcConfigurerAdapter已被弃用。


2
仅仅是一个细节:在Spring Boot应用程序中,你的@Configuration类不应该包含@EnableWebMvc注解(来源)。这可能会阻止其他一些东西的工作,例如springfox-swagger-ui html页面。 - Paulo Merson
4
WebMvcConigurerAdapter已经被弃用,只需要将extends WebMvcConfigurerAdapter改为implements WebMvcConfigurer即可。 - Taylor O'Connor
因为滥用 @EnableWebMvc 而被踩。Spring Boot 不应该与它混合使用。 - emeraldhieu

13
如果您使用的是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。 - UpAllNight
favorPathExtension设置为false时,设置mediaTypes是否有任何影响? - holmis83
2
当favorParameter设置为true时,mediaTypes被使用。这将检查查询参数,因此/blahblah/4?format=xml将解析为application/xml。favorParameter的默认值为false,因此在此示例中设置mediaTypes没有影响。 - Dick Chesterwood
2
嗨,包含上述代码后,如果没有接受头,则会得到默认的JSON。但是,如果我将其设置为application/xml,仍然会得到JSON响应而不是XML?我错过了什么吗? - Sundar G

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接