In my Spring MVC and Rest post, I walked through the creation of a RESTful web service with Spring MVC. Let’s now take a look at JSON.
Spring MVC, from version 3, allows you to return objects directly converted into JSON using the @ResponseBody annotation in a Controller as shown here:
@RequestMapping(method=RequestMethod.GET, value =”/movie/{name}) public @ResponseBody Movie getMovie(@PathVariable String name, Model model){ return new Movie(name); }
In this way, AJAX interactions can be simplified, since you can deal with JSON objects after you interrogate a RESTful web service. In order to achieve that, assuming you are using Maven, you need to include the Jackson mapper dependency to your POM file as shown here:
org.codehaus.jackson jackson-mapper-asl 1.9.5
After that, you need to add to your Spring configuration file the mvc:annotation-driven configuration element and the bean with class ContentNegotiatingViewResolver:
ContentNegotiatingViewResolver, based on the supported mediaType, will determine the right view resolver. In this case the UrlBasedViewResolver would handle text/html content and the MappingJacksonView would handle application/json content. An example of a simple JSON object, containing just the name attribute, returned by the above controller could be:
{name : “Titanic”}
On the client-side, here is some JavaScript code (using jQuery) invoking the web service defined in the first snippet:
$.get(“http://www.example.com/movie/titanic”, function(data){ // data is a JSON object });
The callback will hold the JSON object coming from the server into the data variable. And that wraps up this tip, which will help you return objects directly converted into JSON using Spring MVC.
No comments:
Post a Comment