views:

625

answers:

3

I want many of my controllers to create and return ModelMaps and to have these ModelMaps subsequently sent to/processed by a JsonView. (These controllers will service AJAX requests.) I assume I need setup a ViewResolver; what is the best way to do this? Is there a better alternative to Spring-Json View?

EDIT:

How do I wire a view when my controller returns ModelMap objects rather than ModelAndView objects?

+1  A: 

I'm not sure if it's a 'better' alternative to spring-json, but with Spring 3.0, you can just annotate some methods in your Controller, and it will return json or xml based on the HTTP Accept header.

See this blog post for more information.

Steve K
Thanks; this is nice. Any suggestions if I want to stick with 2.5.x?
Upper Stage
I haven't used spring-json - but it looks reasonable if your using 2.5.x. I used Jersey, and the spring-jersey module before, but that used a different set of annotations (jax-rs). So it wouldn't integrate quite as nicely with your controllers. But it is another alternative https://jersey.dev.java.net/nonav/documentation/latest/user-guide.html#d4e1280
Steve K
+1  A: 

What is the problem with using spring-json view?

This seems like the exact way you would want to handle something like this:

  • Your controller is ignorant of the view technology that will be used, it just returns a viewname and the data (model)
  • You configure a view resolver to transform this model into JSON (or HTML, or Excel, or whatever you would like)
matt b
Thanks; nothing wrong with it, simply asking. Care to add an example of how to configure?
Upper Stage
http://spring-json.sourceforge.net/demoapp.html and http://spring-json.sourceforge.net/quickstart.html
matt b
Thanks @matt b, but these examples return ModelAndView objects.
Upper Stage
That is what Spring MVC Controllers are supposed to return, and what the interface specifies. Can you qualify what you mean by ModelMaps? What type of Controller are you using that returns such an object?
matt b
ModelMap is a part of Spring 2.0's redesigned ModelAndView object, encapsulating a collection of name-value attribute pairs that will be exposed to the view. http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/ui/ModelMap.html
Upper Stage
+1  A: 
/**
 * Custom handler for displaying vets.
 * Note that this handler returns a plain {@link ModelMap} object instead of
 * a ModelAndView, thus leveraging convention-based model attribute names.
 * It relies on the RequestToViewNameTranslator to determine the logical
 * view name based on the request URL: "/vets.do" -> "vets".
 * @return a ModelMap with the model attributes for the view
 */
@RequestMapping("/vets.do")
public ModelMap vetsHandler() {
    return new ModelMap(this.clinic.getVets());
}

It relies on the RequestToViewNameTranslator to determine the logical view name.

Upper Stage