Posts Tagged ‘web mvc’

Spring 3.0 Web MVC and JSON

Over the weekend I got a chance to use Spring 3.0’s MappingJacksonJsonView and ContentNegotiatingViewResolver. I’m very happy with how easy it was to integrate with my code. I didn’t have to do very much at all to get JSON out of my web app.

Why would I want JSON out of the app instead of HTML?  Interoperability is one reason.  Now instead of being bound to one web app, my own, my data can be shuttled to other apps in a commonly understood notation without screen scraping.  Of course we can also use Atom and RSS for data that can be massaged into those formats with the ContentNegotiatingViewResolver as well.  For stuff that can’t coerced into standardized XML, JSON is a great choice.

If you don’t know what JSON is, it’s basically a JavaScript text representation of a map that drills down into your object hierarchy if you have one. Let’s say I want to get my user information. The JSON representation is:

{ "firstname":"Anthony", "lastname":"Chaves", "userid":"123456", "address":{ "street":"A Fake Street", "city": "Bradford", "state":"MA" } }

This JSON is valid JavaScript and parsed by the library of your choice. The first three fields are just string data. The address field is another map that contains data about my address. This is produced because my Java class User has a field of class Address. Address contains the street, city and state fields.

To get the JSON output we should use a MappingJacksonJsonView. This view uses the Jackson library to map our Java objects to JSON. We need the Jackson core and mapper jars on our classpath to make this view work. I just copied them into my WEB-INF/lib directory.

It should be noted that I could not get any combination of configuration and Jackson jar files to work using Glassfish 2.1.1. Deploying the app failed due to a java.lang.VerifyError with the message “Cannot extend a final class.” Duh. The same app worked right from the start on Tomcat 6.0.24.

Because we want to preserve the functionality of the web app and its HTML output we can’t cut out the UrlBasedViewResolver completely. We want the app to function as normal when we get requests for .html files but return JSON when we get requests for .json files. So user.html would be used to get the HTML output of a user page and user.json would be used to get the above JSON output for a different app.

Spring 3.0 has a ContentNegotiatingViewResolver that does just this. Based on the client accept header and the file extension, this view resolver determines the best view resolver to pass the request on to after the controller does its processing.

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="mediaTypes">
    <map>
      <entry key="html" value="text/html"/>
      <entry key="json" value="application/json"/>
    </map>
  </property>
  <property name="viewResolvers">
    <list>
      <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
      </bean>
    </list>
  </property>
  <property name="defaultViews">
    <list>
      <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
        <property name="prefixJson" value="true"/>
      </bean>
    </list>
  </property>
</bean>

For text/html content the ContentNegotiatingViewResolver sends requests on to the old UrlBasedViewResolver after the controller method returns. For application/json or application/javascript requests the ContentNegotiatingViewResolver passes the request on to the MappingJacksonJsonView. This view parses the object tree into JSON and gives us the output we want.

The object tree is based on the objects in the Spring Web MVC model. This means we have to add them to a ModelMap object in the controller. In an HTML-based web app we might store data in the HttpSession object. For JSON we need it in the ModelMap. Let’s say we’re adding a tag to something.

@RequestMapping(method=RequestMethod.GET)
public String getBookmarksWithTag(@RequestParam(value="tag") String tag, HttpSession session, ModelMap model) {
  User user = (User) session.getAttribute("user");

 doSomethingUseful(user);

  model.addAttribute(user);
  return "tags";
}

By placing the User object into the ModelMap, Spring has a reference to it when it comes time to make some JSON. We still return a string, “tags”, so the UrlBasedViewResolver still returns the same jsp for text/html content. After this controller method returns, Spring takes the result and sends it to the ContentNegotiatingViewResolver. The “tags” return value is not used if the request is sent to the MappingJacksonJsonView. It has no use for jsps. If the request were for text/html the “tags” string would be used by the UrlBasedViewResolver.

Like I said, I’m happy with the new REST support in Spring 3.0 Web MVC. It’s certainly lagging behind Rails in trendy features but it’s far more flexible overall. There is a certain “style” to writing web apps that Rails guys have. I’m convinced it’s just as easy to use this style in Spring as it is to do it in Rails but the huge amount of extraneous documentation and classes in Spring makes it more difficult than it should be to get down to business. I’m not making a statement about the Spring framework itself, it’s certainly possible to do everything I want and need. I just haven’t seen a good style guide or cookbook for RESTful web apps. Maybe it’s because some of the features are still so new, being just added to the 3.0 branch. Maybe we just haven’t found the right idioms yet.