Upperstage
Upperstage

Reputation: 3757

Spring MVC 2.5, JsonView, and ModelMap

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?

Upvotes: 1

Views: 4822

Answers (3)

Upperstage
Upperstage

Reputation: 3757

/**
 * 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.

Upvotes: 1

matt b
matt b

Reputation: 140051

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)

Upvotes: 1

Steve K
Steve K

Reputation: 19596

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.

Upvotes: 1

Related Questions