2017-06-02 31 views
1

我有一个简单的@RestController,并且想要根据http标头content-type同时回复JSONXML如何在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头?

+0

拆分方法的JSON和XML或此链接可能会帮助https://stackoverflow.com/questions/26676613/multiple-scenarios-requestmapping-produces-json-xml-together-with-accept-or-res –

+2

只是好奇 - 你不应该使用'Accept'头文件来确保内容类型? – Antoniossss

+0

哈哈,我刚刚看到同样的答案,并猜测我是对的:) – Antoniossss

回答

6

您应该使用Accept表头不是Content-Type。第一个是请求,第二个包含在回复中。

+0

哇,很棒的接球。这确实是解决方案! – membersound