我正在重新构建旧的rest api,需要保持与之的兼容性。旧的api使用servlet并与xml和json一起使用。逻辑如下:
如何使用Spring MVC(使用Spring Boot)获得相同的结果?我试图覆盖config类中的configureContentNegotiation,但它似乎不起作用:
@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
@ComponentScan(basePackages = {"..."})
public class AppConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentTypeStrategy((NativeWebRequest request) -> {
String header = request.getHeader("Content-Type");
MediaType mediaType;
if (Objects.isNull(header)) {
mediaType = MediaType.APPLICATION_XML;
} else switch (header) {
case MediaType.TEXT_XML_VALUE:
case MediaType.APPLICATION_XML_VALUE:
case MediaType.APPLICATION_JSON_VALUE:
case MediaType.APPLICATION_JSON_UTF8_VALUE:
mediaType = MediaType.valueOf(header);
break;
default:
mediaType = MediaType.APPLICATION_XML;
}
return Arrays.asList(mediaType);
});
}
/*the rest of configuration*/
}
答案 0 :(得分:0)
您可以将HttpServletRequest用于请求标头值。
@Autowire
HttpServletRequest request;
private String getContentType() {
return request.getHeader("Content-Type");
}