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.
 

Reference: Spring MVC REST Calls With Ajax from our JCG partner Jerome Versrynge at the Technical Notes blog.

Related Whitepaper:

Introduction to Web Applications Development

Kick start your web apps development with this introductory ebook!

This 376 page eBook 'Introduction to Web Applications Development', starts with an introduction to the internet, including a brief history of the TCT/IP protocol and World Wide Web. It defines the basic concepts for web servers and studies the case of Apache, the most used webserver, while other free software webservers are not forgotten. It continues with webpage design focusing on HTML and JavaScript. XML Schemas, their validation and transformation are covered as well as dynamic webpages built with CGI, PHP or JSP and database access.

Get it Now!  

One Response to "Spring MVC REST Calls With Ajax"

  1. 廖师虎 says:

    Nice! Thanks!

Leave a Reply


× eight = 16



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books