如何在没有提供Accept标头的情况下在Spring MVC中设置默认内容类型? [英] How to set the default content type in Spring MVC in no Accept header is provided?

查看:171
本文介绍了如何在没有提供Accept标头的情况下在Spring MVC中设置默认内容类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在没有Accept标头的情况下将请求发送到我的API,我想将JSON设置为默认格式.我的控制器中有两种方法,一种用于XML,另一种用于JSON:

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.  
 }

当我发送不带Accept标头的请求时,将调用getXmlData方法,这不是我想要的.如果没有提供Accept标头,是否可以告诉Spring MVC调用getJsonData方法?

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?

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

There is a defaultContentType field in the ContentNegotiationManagerFactoryBean that does the trick.

推荐答案

来自 Spring文档,您可以使用Java配置来做到这一点,

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);
  }
}


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


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.

这篇关于如何在没有提供Accept标头的情况下在Spring MVC中设置默认内容类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆