Monday, 29 October 2012

Returning a JSON in Spring (With Annotations)

This post provides the simplest example to return a JSON from a Spring controller. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-Returning-A-JSON directory.

For a full Spring MVC REST calls with Ajax example, see here.

Dependencies

On top of current dependencies, we add the Jackson mapper dependency:
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.10</version>
</dependency>
This dependency enables the conversion of Java objects into a JSON representation.

Data

For this example, we use a simple SomeData class:
public class SomeData {

    private String name;
    private long time;

    public SomeData(String name, long time) {
        this.name = name;
        this.time = time;
    }

    public SomeData() {
        name = "";
        time = System.currentTimeMillis();
    }

    // Setters & Getters

}

Controller

We modify our controller as following:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

    @RequestMapping(value="/getJSON/{name}", method = RequestMethod.GET)
    public @ResponseBody SomeData getJSON(@PathVariable String name) {

        SomeData result
            = new SomeData(name, System.currentTimeMillis());

        return result;

    }

}
The getJSON() method has special annotations usage:
  • @RequestMapping's value contains {name} which will be extracted by Spring an inserted as the parameter value in the method.
  • @ResponseBody's indicates that the body of the response to the user's request must be filled with what is returned by the method. Here, we return a SomeData object. Since we have added the Jackson dependency, Spring will automatically detect it and perform the conversion of this object into its JSON representation.
  • @PathVariable extracts the parameter's name from the URL's {name} and sets its as the parameter value in the getJSON() method.

JSP Index Page

Our index page remains very simple:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Welcome !!!</title>
</head>
<body>
    <h1>
    Welcome To Spring Returning A JSON !!!
    </h1>
    <a href="<c:url value='/getJSON/Arthur'/>">Get JSON for Arthur !!!</a>
</body>
</html>
It contains a link making a call to /getJSON/Arthur.

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8383/spring-returning-a-json/.

The home page will display:


Click on the link to retrieve the JSON:



More Spring related posts here.

3 comments: