Spring 3.1或更高版本@RequestMapping使用/生成

问题描述:

我对消费有疑问,并生成部分 @RequestMapping 。我有一个端点,我想接受JSON和XML,并在传入JSON时返回JSON,并在传入XML时返回XML。我需要做些什么特别的工作才能使其工作?

I have a question in regards to the consumes and produces part of the @RequestMapping. I have an endpoint that I want to accept both JSON and XML and return JSON when JSON is passed in and return XML when XML is passed in. Is there anything special that I have to do to make this work?

示例代码如下所示。

@RequestMapping(value = "/something", method = PUT, 
                consumes = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE}, 
                produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})
public SomeObject updateSomeObject(SomeObject acct) {
    return doStuff(acct);
}

这会按照我期望的方式工作,还是需要两个端点 updateSomeObjectXML updateSomeObjectJson 来处理这两种情况?

Will this work the way I'm expecting or do I need two endpoints updateSomeObjectXML and updateSomeObjectJson to handle both cases?

谢谢,
Mike

Thanks, Mike

来自Spring博客的文章 - 使用Spring MVC进行内容协商 - 提供有关内容协商如何与Spring MVC协同工作的详细信息,简要介绍一下处理XML和JSON的相同端点,你的映射是正确的,总结来自文章:

The article from the Spring blog - Content Negotiation using Spring MVC - provides details on how content negotiation works with Spring MVC, in brief if you want the same endpoint to handle XML and JSON, your mapping is correct, to summarize from the article:


  1. 使用路径扩展 - 你可以发送一个json到 /something.json 和xml到 /something.xml 并期待同样的事情返回

  1. Use path extension - you can send a json to /something.json and xml to /something.xml and expect the same thing on the way back

使用接受标头,使用值 application / json application / xml 并使用 Content-Type 指定提交的媒体类型。

Use the Accept header, use a value of application/json or application/xml and use Content-Type to specify the submitted media type.