Home » Java » Enterprise Java » Spring MVC REST Calls With Ajax

About Jerome Versrynge

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

One comment

  1. Nice! Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

*


four × 8 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.