Mike Baglio Jr. Mike Baglio Jr. - 5 months ago 67
Java Question

Spring 3.1 or Later @RequestMapping Consumes/Produces

I have a question in regards to the consumes and produces part of the @RequestMapping annotation. 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?

Sample code is listed below.

@RequestMapping(value = {"/something"}, method = RequestMethod.PUT,
public SomeObject updateSomeObject(SomeObject acct) {
return doStuff(acct);

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



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.