Spring boot - setting default Content-type header if it's not present in request

情到浓时终转凉″ 提交于 2021-02-08 16:59:13

问题


I'm having the following problem: suppose I sometimes receive POST requests with no Content-type header set. In this case I want to assume that Content-type=application/json by default.

Can I achieve this somehow using spring boot features and not using filters?

Thanks


回答1:


As of Spring Boot 2.x, you need to create a class that extends the WebMvcConfigurer interface, e.g.:

@Configuration
class WebMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation( ContentNegotiationConfigurer configurer )
    {
        configurer.defaultContentType( MediaType.APPLICATION_JSON );
    }
}

Under 1.x, you could do the same thing with WebMvcConfigurerAdapter, which is now deprecated.

This will affect both request and response bodies, so if you do not have a "produces" parameter explicitly set, and you wanted something other than application/json, it's going to get coerced to application/json.



来源:https://stackoverflow.com/questions/48216052/spring-boot-setting-default-content-type-header-if-its-not-present-in-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!