Mike Baglio Jr. Mike Baglio Jr. - 17 days ago 11
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,
consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},
produces = MediaType.APPLICATION_JSON_VALUE, MediaType.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

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.