Sunday, 4 November 2012

Fetching JSON With Ajax In Spring MVC Context

This post explains how to fetch a JSON using Ajax from a Spring MVC web application. It is based on the Spring MVC With Annotations and Serving Static Resources With Spring MVC examples. The code is available on GitHub in the Spring-Fetching-JSON-With-Ajax directory.

Main Index Page

We use a simple index.jsp page, where we set a button that fetches a JSON, and a <div> where the result will be displayed:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="" %>
<!doctype html>
<html lang="en">
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <script type="text/javascript"
  <script type="text/javascript"
    src="<c:url value='/resources/js/FetchingJsonWithAjax.js'/>">
  <title>Welcome To Fetching JSON With Ajax !!!</title>
    <h1>Fetching JSON With Ajax !!!</h1>
    <div id="theJson"></div>
    <button type="button" onclick="fetch_json()">
        Fetch JSON


On the button, we attach the fetch_json() Javascript method, which is called when the button is clicked:
var fetch_json = function() {

        type: 'GET',
        url:  "/spring-fetching-json-with-ajax/getJSON",
        dataType: 'json',
        async: true,
        success: function(result) {

            var tmp = "Fetch time is: " + result.milliTime + " !"
               + "and the JSON is:"
               + JSON.stringify(result);


        error: function(jqXHR, textStatus, errorThrown) {
            alert("Issue fetching the JSON: "
                + textStatus + " "
                + errorThrown + " !");


If successful, we set the result on the <div>, else we pop-up a message with the error.


The controller is kept simple, and a MilliTime object is returned for the Ajax call:
public class MyController {

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

    @RequestMapping(value="/getJSON", method = RequestMethod.GET)
    public @ResponseBody MilliTimeItem getJSON() {
        return new MilliTimeItem(System.currentTimeMillis());


Running The Example

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


After clicking on the Fetch JSON button, something similar to the following will be displayed:

More Spring related posts here.

No comments:

Post a comment