Skip to content

March 29, 2011

JSON / Ajax in Spring MVC

How do you configure your Spring MVC web application to serve JSON for Ajax? It is not difficult. You probably have a view resolver in your dispatcher-servlet.xml that looks like this:

<bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:viewClass="org.springframework.web.servlet.view.JstlView"
        p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp" />

In order to serve JSON content, you need to use the ContentNegotiatingViewResolver. The configuration looks like this:

<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 id="viewResolver"
                class="org.springframework.web.servlet.view.InternalResourceViewResolver"
                p:viewClass="org.springframework.web.servlet.view.JstlView"
                p:prefix="/WEB-INF/jsp/"
                p:suffix=".jsp" />
        </list>
    </property>
    <property name="defaultViews">
        <list>
            <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
        </list>
    </property>
</bean>

Here, I’m using the Jackson Java-JSON processor. You will need the appropriate Jackson jar files in your classpath.

Then, in your controller, an annotated method to test it out:

@RequestMapping(value="/test", method= RequestMethod.GET)
    public ModelMap test() {
        int[][] integers = new int[4][2];
        String[] strings = {"alabama", "alaska", "arkansas"};
        for (int i = 0; i &lt; integers.length; i++) {
            int num = i + 1;
            integers[i][0] = num;
            integers[i][1] = num * num;
        }
 
        ModelMap map = new ModelMap("xyz", 123);
        map.addAttribute("intValues", integers);
        map.addAttribute("stringValues", strings);
        return map;
    }

The URL will look something like “http://localhost:8084/YourApp/test.json”. Try it out. The JSON string returned will be:

{ "intValues" :
    [
      [ 1, 1 ],
      [ 2, 4 ],
      [ 3, 9 ],
      [ 4, 16 ]
    ],
  "stringValues" :
      [ "alabama",
        "alaska",
        "arkansas"
      ],
  "xyz" : 123
}

The way you request this JSON-encoded data with jQuery is by using the .getJSON method, like so:

$.getJSON("/YourApp/test.json",
              function(data) {
                  // do something with the data
                  alert(data.xyz);
            });

Configuring Spring MVC to serve data in JSON format is as easy as that.

Read more from Java

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments