Spring 3.1 or Later @RequestMapping Consumes/Produces

后端 未结 3 1755
一生所求
一生所求 2020-12-24 02:40

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 JS

相关标签:
3条回答
  • 2020-12-24 02:49

    Well,

    consumes/produces takes String[] as a parameter (see RequestMapping from Spring's documentation) so I believe it will work. You can also try headers = "content-type=application/json,application/xml".

    0 讨论(0)
  • 2020-12-24 02:54

    Short answer:
    Annotate the method with @ResponseBody, and the method parameter with @RequestBody, and it will work (no need for 2 methods).

    Explanation:
    First, produces and consumes attributes are used to narrow the mapping types. By default the first HttpMessageConverter found, that matches the media type requested, will be used.

    Second, client requests a media type by giving the media type in:
    - Accept request header
    - URL sufix (http: //....//some .xml => "application/xml" media type requested)
    - URL format parameter (.../some?format=xls)

    Third, produces in combination with @ResponseBody will produce the object in the requested media type (nice for GET requests, when you need to send something back to the client), and consumes in combination with @RequestBody will consume the object with the requested media type (nice for POST requests, when you need to get something from the client).

    Four, when @ResponseBody not used, HttpMessageConverters are not used. Rather ViewResolvers kick in and produce a view (HTML, PDF...), and the return type should follow the rules that accompany ViewResolvers (check default view resolver and InternalResourceViewResolver for more).

    Hope it helps.

    Other sources:
    http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#consumes-- http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

    0 讨论(0)
  • 2020-12-24 02:56

    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. 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

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

    0 讨论(0)
提交回复
热议问题