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>
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; } }
- @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>
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.
Thanks! Works perfect!
ReplyDeleteAwesome!
ReplyDeleteGood work
ReplyDelete