Can the same method in a controller be used for both JSP and other MIME types (like XML and JSON)?
I know of the following ways to resolve views in Spring MVC.
- Return a
Stringwith the view name and add attributes to theModelorModelMap - Return a
ModelAndViewwith the view name and model - Return an
Objectwith a@ResponseBodyannotation
I use 1 or 2 when I am dealing with JSP and 3 when I want to return JSON or XML.
I know I can use two methods and with the @RequestMapping(headers="accept=application/xml") or @produces annotations to define which MIME types they handle, but is it possible to do this in just one method?
The controller logic is pretty simple and it seems like unnecessary duplication to have two different methods mapped which return the same exact model, or is this just simply the way it’s done?
Yes, this is straight forward in Spring MVC 3.x…
You basically write your controller methods for just normal JSP page views and then you configure a
ContentNegotiatingViewResolverbean in your Dispatcher servlet config., which looks at the requested mime-type (or file extension) and returns the appropriate output type.Follow the instructions here: Spring 3 MVC ContentNegotiatingViewResolver Example