Spring 3.1 or Later @RequestMapping Consumes/Produces

Mike Baglio Jr. picture Mike Baglio Jr. · Oct 20, 2014 · Viewed 84.7k times · Source

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?

Sample code is listed below.

@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);
}

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

Thanks, Mike

Answer

Biju Kunjummen picture Biju Kunjummen · Oct 20, 2014

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.