我有一个简单的@RestController
,并且想要根据http标头content-type
同时回复JSON
或XML
。如何在spring-mvc中为响应启用多个内容类型?
问题:我总是只得到XML
响应,从来没有JSON。当然,我使用Content-Type: application/json
作为http头。
以下配置可能会丢失什么?
@RestController
public void MyServlet {
@RequestMapping(value = "test", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public MyResponse test() {
return new MyResponse();
}
}
@XmlRootElement
public class MyResponse {
private String test = "somevalue";
//getter, setter
}
的pom.xml:
<!-- as advised in: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
</dependency>
有趣的是:如果我切换产生的语句: produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
, 然后我一直都想与JSON
出永不XML
!
所以问题是:为什么第一个MediaType总是有优先权,并且从未考虑过http头?
拆分方法的JSON和XML或此链接可能会帮助https://stackoverflow.com/questions/26676613/multiple-scenarios-requestmapping-produces-json-xml-together-with-accept-or-res –
只是好奇 - 你不应该使用'Accept'头文件来确保内容类型? – Antoniossss
哈哈,我刚刚看到同样的答案,并猜测我是对的:) – Antoniossss