Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Respond to html, json and xml with Spring MVC content negotiation

All examples that I have found around internet were about to use content negotiation with json, xml etc. Is there any chance to have only one method producing all kind of contents, like:

@RequestMapping(produces={"text/html","application/json"})
public List<Product> list() {
    return productDAO.list();
}

I tried to use the ContentNegotiationManager, but nothing worked for me.

like image 684
Alberto Souza Avatar asked Dec 10 '25 05:12

Alberto Souza


1 Answers

One method can return responses of different content types. Some you can get with default settings, some you have to additionally configure. Take for example a following method, quite similar to yours,

@RequestMapping(value="/response", method=RequestMethod.GET, produces={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public @ResponseBody Foo multipleTypes() {
    return new Foo();
}

this method is capable of returning both XML and JSON, even more Spring MVC will automatically configure the converters if you have JAXB2 and Jackson libs on the classpath.

When reasoning whether it will return an XML or JSON its where content negotiation comes to play. If the request is suffixed with a path e.g. /response.json or /response.xml the response will be set based on it. The resolution can be based on a parameter as well, so /response?format=xml. Finally, if the request has an Accept header set to XML or JSON a response will be converted to the respective type. This constitutes a PPA strategy (Path, Parameter, Accept).

In other words, if you provide a proper converter implementations and configure them properly (some are available out of the box), you can get a single method that returns different representations, that you can control based on the PPA strategy.

Content Negotiation Using Spring MVC is a great post on Spring's Blog site with working examples.

like image 99
Master Slave Avatar answered Dec 11 '25 21:12

Master Slave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!