Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Wednesday, 7 November 2012

Spring MVC REST Calls With Ajax

This post provides a simple example of REST calls to a Spring MVC web application. It is based on the Serving Static Resources With Spring MVC and Fetching JSON With Ajax In Spring MVC Context example. The code is available on GitHub in the Spring-REST-With-Ajax directory.

Main Page

Our main page contains four buttons linked to Javascript functions performing Ajax calls:
...
<body>
<h1>Welcome To REST With Ajax !!!</h1>
<button type="button" onclick="RestGet()">GET</button>
<button type="button" onclick="RestPut()">PUT</button>
<button type="button" onclick="RestPost()">POST</button>
<button type="button" onclick="RestDelete()">DELETE</button>
</body>
...

Javascript

Our Javascript file contains the four functions:
var prefix = "/spring-rest-with-ajax";

var RestGet = function() {
        $.ajax({
        type: 'GET',
        url:  prefix + "/MyData/" + Date.now(),
        dataType: 'json',
        async: true,
        success: function(result) {
            alert("At " + result.time
                + ": " + result.message);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " " + jqXHR.responseText);
        }
   });
}

var RestPut = function() {

    var JSONObject= {
        "time": Date.now(),
        "message": "User PUT call !!!"
    };
 
    $.ajax({
        type: 'PUT',
        url:  prefix + "/MyData",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(JSONObject),
        dataType: 'json',
        async: true,
        success: function(result) {
            alert("At " + result.time
                + ": " + result.message);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " " + jqXHR.responseText);
        }
    });
}

var RestPost = function() {
        $.ajax({
        type: 'POST',
        url:  prefix + "/MyData",
        dataType: 'json',
        async: true,
        success: function(result) {
            alert("At " + result.time
                + ": " + result.message);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " " + jqXHR.responseText);
        }
    });
}

var RestDelete = function() {
        $.ajax({
        type: 'DELETE',
        url:  prefix + "/MyData/" + Date.now(),
        dataType: 'json',
        async: true,
        success: function(result) {
            alert("At " + result.time
                + ": " + result.message);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " " + jqXHR.responseText);
        }
    });
}

Controller

Our controller captures the REST calls and returns a JSON. In a real applications, one would perform CRUD operations rather than returning JSONs:
@Controller
@RequestMapping(value = "/MyData")
public class MyRESTController {

    @RequestMapping(value="/{time}", method = RequestMethod.GET)
    public @ResponseBody MyData getMyData(
            @PathVariable long time) {
  
        return new MyData(time, "REST GET Call !!!");
    }
 
    @RequestMapping(method = RequestMethod.PUT)
    public @ResponseBody MyData putMyData(
            @RequestBody MyData md) {
  
        return md;
    }
 
    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody MyData postMyData() {
 
        return new MyData(System.currentTimeMillis(),
            "REST POST Call !!!");
    }

    @RequestMapping(value="/{time}", method = RequestMethod.DELETE)
    public @ResponseBody MyData deleteMyData(
            @PathVariable long time) {
  
        return new MyData(time, "REST DELETE Call !!!");
    }
}

Running The Example

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

  http://localhost:8585/spring-rest-with-ajax/

The main page will be displayed:



If you click on any button, a pop-up will be displayed:


See here for more about REST • More Spring related posts here.

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="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script type="text/javascript"
    src="<c:url value='/resources/js/FetchingJsonWithAjax.js'/>">
  </script>
  <title>Welcome To Fetching JSON With Ajax !!!</title>
</head>
<body>
    <h1>Fetching JSON With Ajax !!!</h1>
    <div id="theJson"></div>
    <button type="button" onclick="fetch_json()">
        Fetch JSON
    </button>
</body>
</html>

Javascript

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

    $.ajax({
        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);

            $("#theJson").html(tmp);

        },
        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.

Controller

The controller is kept simple, and a MilliTime object is returned for the Ajax call:
@Controller
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:

  http://localhost:8585/spring-fetching-json-with-ajax/

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



More Spring related posts here.