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

mem*_*und 1 java xml rest spring json

我有一个简单的,@RestController并希望响应两者JSONXML取决于http标头content-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
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

有趣的是:如果我切换生产声明: produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})那么我总是JSON走出去,永远不会XML!

所以问题是:为什么第一个MediaType总是有优先权,http头从不考虑?

Ant*_*sss 6

你不应该使用Accept标题Content-Type.第一个是请求,第二个是响应.