如何在spring-mvc中为响应启用多个Content-Types?

时间:2017-06-02 13:48:39

标签: java json xml spring rest

我有一个简单的@RestController,并希望根据http标头JSON同时回复XMLcontent-type

问题:我总是只获得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头从不被考虑在内?

1 个答案:

答案 0 :(得分:6)

您应该使用Accept标题Content-Type。第一个是请求,第二个是响应。