Spring MVC JSON Cheat Sheet

July 5th 2013 by Samuel Rossille

In every client / server application, we need a communication layer, and we want it to be slick, easy to use and to require as little repetitive tasks as possible.

In my opinion, jQuery + JSON + Spring MVC is a very good combo - if not the best.

There are a lot of good tutorials about Spring MVC. This is not a tutorial. It's just a cheat sheet, where you can find everything you need to copy/paste to have a fully functionnal jQuery + JSON + Spring MVC stack.

Code Snippets

What I like with these technologies is that there is almost nothing around the business code, as you can see in the code samples below.

URL Mapping convention: Spring MVC allows to define mappings between URL and Java class methods.

By convention, these URLs look like this: mvc/business-domain/action, where:

Client-side: POST Request, data in request body

$.ajax({
    method: 'POST',
    url: "mvc/user/save",
    contentType: 'application/json',
    data: JSON.stringify({firstName: 'John', lastName: 'Doe'})
})
.done(function(result) {
    // Whatever
}

Client-side: GET Request, simple parameter in URL

$.get("mvc/user/get/" + id)
.done(function(userDTO) {
    // Whatever
});

Server-side: Just a simple Java class with annotations, the Controller

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {
    private static Map<String, UserDTO> users = new HashMap<String, UserDTO>();

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public @ResponseBody UserDTO getUser(@PathVariable String id) {
        UserDTO user; 

        // This would be replaced with actual business code
        user = users.get(id);

        return user;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public @ResponseBody String saveUser(@RequestBody UserDTO user) {

        // Mock persistence
        user.setId(UUID.randomUUID().toString());
        users.put(user.getId(), user);

        return user.getId();
    }

    @RequestMapping(value = "/get-all-users", method = RequestMethod.GET)
    public @ResponseBody Iterable<UserDTO> getAllUsers() {
        Iterable<UserDTO> allUsers; 

        // This would be replaced with actual business code
        allUsers = users.values();

        return allUsers;
    }
}

Configuration

Dependencies

If you use maven, just pick the dependencies here. Otherwise... well... you know better than me what to do ;=)

<!-- First things first, at the time I created this project, 
many version more recent than 3.0.5-RELEASE have issues 
with JSON mapping. For production use I recommend to use 
3.0.5-RELEASE -->
<properties>
    <spring.version>3.0.5.RELEASE</spring.version>
    <jackson.version>1.9.10</jackson.version>
</properties>

<dependencies>
    <!-- Spring 3 dependencies -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <!-- Jackson JSON Mapper -->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>${jackson.version}</version>
    </dependency>
</dependencies>

MVC Dispatcher Servlet

Add Spring MVC dispatcher servlet and servlet mapping in web.xml. Note that here we choose "mvc" as a prefix for everything that will be handled by Spring MVC, but anything that pleases you goes.

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/mvc/*</url-pattern>
</servlet-mapping>

Add the dispatcher servlet configuration file: WEB-INF/mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <context:component-scan base-package="springmvccheatsheet.user" />
    <mvc:annotation-driven />
</beans>

Conclusion

The complete source code of the samples is available on github. Many thanks to my Spring teacher for his numerous and interesting tutorials.

Comments

Ram: Hi It is very useful and a good cheat sheet for quick reference. The WEB-INF/mvc-dispatcher-servlet.xml had missed beans schemaLocation. Pasting compelete xml. ----------------------------------------------------- ---------------------------------------------- Good luck!!