In my previous post, I documented a scenario that I encountered while setting up a JSON view resolver in a Spring MVC project. Let me take a step back and explain my motivations for why I wanted a JSON view resolver.
In any Spring MVC application, Controller classes are responsible for processing some data, then returning a ModelAndView . Typically views eventually return HTML either directly from a JSP or through a templating framework like Tiles. However, custom views can provide output such as Excel or PDF files. In my case, I wanted an easy way to return a JSON response from certain Controller methods that would be called from an Ajax request.
HTML is a perfectly valid response to an Ajax request; often the Javascript processes an HTML response and then inserts the HTML into a page. But occasionally JSON makes more sense, like when a page simply needs to know something about what is going on back on the server without displaying anything to the user(for example, whether the user has a valid session that has not timed out). JSON is the native format of Javascript, so it is a convenient way to return a response to a Javascript client.
I found a great project called Spring Json View that offers all the features of Spring MVC like validation, exception handling, and error handling and automatically converts the Model to a JSON object. It was probably a bit more than I needed for what I was trying to accomplish, but I was working on an internal company project and one of our secondary goals was to build skills and identify patterns that would be useful on future projects. So I tested it out for this simple scenario, and I expect that this pattern could be useful on future projects.
Check out the configuration snippets from my previous post to see how I integrated Spring Json View into Spring MVC.
Also, here’s a quick example of how a controller method can use it:
[code lang=”java”]
@RequestMapping(method = RequestMethod.GET)
public ModelAndView isLoggedIn(ModelMap model) {
model.addAttribute(“loggedIn”,
!SecurityContextHolder.getContext().getAuthentication().getName().equals(“guest”));
return new ModelAndView(“jsonView”, model);
}
[/code]