简体   繁体   English

在springboot应用程序中如何设置默认头(如果不存在)

[英]In springboot application how to set default header if not present

I have written a method with get request mapping it gives list of users. 我已经编写了带有获取请求映射的方法,该方法给出了用户列表。 As jakson binding dependency is there is gives response in JSON. 由于jakson绑定依赖性,因此在JSON中给出了响应。 I've also dependency for XML which is Jackson Dataformat XML.So, if Accept is application/json it returns the response in JSON and if it is in application/xml it returns in XML.But by default it gives JSON response. 我也依赖于XML,即Jackson Dataformat XML。因此,如果Accept为application / json,则以JSON返回响应;如果它为application / xml,则以XML返回。但是默认情况下,它给出JSON响应。 SO, I wanted to add Accept header if not present and make it's default value as application/xml. 因此,我想添加Accept头(如果不存在)并将其默认值设置为application / xml。

@GetMapping(path="/getAll")
    public List<User> getUsers(@RequestHeader(value= "Accept" ,required=false, defaultValue="application/xml") String Accept)
    {
        return service.findAll();
    }

But in above case, the header is not setting. 但在上述情况下,标头未设置。

In order to do so, you need to modify your controller method to return ResponseEntity<List<User>> as following: 为此,您需要修改控制器方法以返回ResponseEntity<List<User>> ,如下所示:

@GetMapping(path="/getAll")
public ResponseEntity<List<User>> getUsers(@RequestHeader(value= "Accept" ,required=false, defaultValue="application/xml") String Accept) {

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setLocation(location);
    responseHeaders.set("Accept", "Value");
    return new ResponseEntity<List<User>>(service.findAll(), responseHeaders, HttpStatus.CREATED);
}

If you just want to respond XML from your spring boot application, use the following custom webMvcConfiguration . 如果您只想从Spring Boot应用程序响应XML,请使用以下自定义webMvcConfiguration Setting a default Accept header just to respond XML does not seem like a good idea. 设置默认的Accept标头只是为了响应XML似乎不是一个好主意。

@Configuration
public class WebMvcConfiguration {

    @Bean
    public WebMvcConfigurer myWebMvcConfigurer() {
        return new WebMvcConfigurerAdapter() {

            @Override
            public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
                configurer.defaultContentType(MediaType.APPLICATION_XML);
            }
        };
    }
}

if you are already using a custom WebMvcConfigurerAdapter , just override the configureContentNegotiation(...) method as above. 如果您已经在使用自定义WebMvcConfigurerAdapter ,则只需重写上面的configureContentNegotiation(...)方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM