Spring MVC and Json with JQuery

As we already seen from our previous tutorial that Spring MVC makes AJAX implementation really easy in web applications. In this tutorial we will, go one step ahead and learn how to provide Json response to the client (browser) in Spring MVC web application.

We will use JQuery to make ajax call to server and to parse json response that we will get from server.

This tutorial is assuming that you have read previous tutorial of Ajax with Spring MVC 3 using Annotations and JQuery. If you have not read it, it is recommended to read.

Tools Used :

  • Spring MVC 3.0.3
  • Eclipse Indigo 3.7
  • Tomcat 6
  • Jdk 1.6
  • JQuery 1.4.2
  • Jackson 1.5.3

You have have noticed that we will use a new tool in our json example with Spring MVC i.e. Jackson. Jackson is nothing but a json processor that contains json encoder and decoder that converts an object to json and vice verse.

So, we have to add two jar files to make Jackson processor available to the Spring Web MVC Framework.

  • jackson-core-asl-1.5.3
  • jackson-mapper-asl-1.5.3

We will change three files in our “List Student” example to work with Json response. Following are the changes :

  1. We will create a new domain object(JsonResponse.java) that will contain json response with two fields status and result.
  2. Will change our controller (UserController.java) to return the instance of JsonResponse class that will contain the result.
  3. Will change out JavaScript code in jsp (AddUser.jsp) to parse json response and update the page.

JsonResponse.java

Following is the code in JsonResponse.java :


package com.raistudies.domain;

public class JsonResponse {
    private String status = null;
    private Object result = null;

    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public Object getResult() {
        return result;
    }
    public void setResult(Object result) {
        this.result = result;
    }
}

It contain two properties, “status” and “result”. “status” field is of type String and will contain “FAIL” or “SUCCESS”. “result” will contain the other data that are to be send back to the browser.

UserController.java


@RequestMapping(value="/AddUser.htm",method=RequestMethod.POST)
public @ResponseBody JsonResponse addUser(@ModelAttribute(value="user") User user, BindingResult result ){
    JsonResponse res = new JsonResponse();
    if(!result.hasErrors()){
        userList.add(user);
        res.setStatus("SUCCESS");
    }else{
        res.setStatus("FAIL");
    }
   res.setResult(user);
   return res;
}

We have change return type of “addUser” to JsonResponse. As the return type of method is annotated with @ResponseBody and we will return an object, so Spring will automatically convert the instance of JsonResponse to Json string using Jackson and return to the browser. This auto conversion will done only if jar files of Jackson are present on classpath.

AddUser.jsp

Let us see how JQuery will handle the Json response get from the server. Following is the code :


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Users using ajax</title>
<script src="/GettingJsonDataJQuery/js/jquery.js"></script>
<script type="text/javascript">
function doAjaxPost() {
// get the form values
var name = $('#name').val();
var education = $('#education').val();

$.ajax({
    type: "POST",
    url: "/GettingJsonDataJQuery/AddUser.htm",
    data: "name=" + name + "&education=" + education,
    success: function(response){
        // we have the response
        if(response.status == "SUCCESS"){
            $('#info').html("User has been added to the list successfully.<br>"+
            "The User Details are as follws : <br> Name : "
            + response.result.name + " <br> Education : " + response.result.education);
            $('#name').val('');
            $('#education').val('');
        }else{
            $('#info').html("Sorry, there is some thing wrong with the data provided.");
        }
    },
    error: function(e){
        alert('Error: ' + e);
    }
});
}
</script>
</head>
    <body>
        <h1>Add Users using Ajax ........</h1>
        <table>
            <tr><td>Enter your name : </td><td> <input type="text" id="name"><br/></td></tr>
            <tr><td>Education : </td><td> <input type="text" id="education"><br/></td></tr>
            <tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
            <tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>
         </table>
         <a href="/GettingJsonDataJQuery/ShowUsers.htm">Show All Users</a>
    </body>
</html>

As you can see, Jquery is sending Ajax request to the server as it done in previous tutorial of Ajax. Only difference will be that the response variable in the success method will be a Json object instead of string response. Jquery will automatically convert the response to Json object and pass to the success function where we can use it as object.

With these changes, create the war file and deploy it to Tomcat 6 server and hit the url in browser. You will get following User form :

Ajax Form For JSon Response using Spring MVC 3

Ajax Form For JSon Response using Spring MVC 3

Now, enter the name of the Student and Education in the form and click on “Add Users” button. You will get following screen without page refresh :

Ajax Success Form For JSon Response using Spring MVC 3

Ajax Success Form For JSon Response using Spring MVC 3

Then, if you want to see the list of the users added, just click on the link “Show All Users”. It will show you the list of the users as following :

Ajax Form Result For JSon Response using Spring MVC 3

Ajax Form Result For JSon Response using Spring MVC 3

Is not it a fun to do the things in Spring MVC ? :) I really enjoy coding with Spring MVC and Jquery. Do you ?

You can download source and war file of the example from following links :

Source : Download

War : Download

Related Posts:

Leave a comment ?

11 Comments.

  1. Good Tutorial for the newbai. i am also newbai in json + spring i found this one good tutorial, but please could you give us the code to pass addstudent detail through json object to controller

    • Thanks Sajid…
      About your query, as we have passed name and education to the controller, you can pass as much as fields you need in your addstudent detail controller. Just use the same technique.

  2. Well projected example. Can you post an example on Jquery’s JqPlot with Spring MVC? Something like, Add students (already done here) extend it to categorizing number of MBA students, B.Tech students and plot a bar chart or pie chart

    • First of all thanks for your comment.
      Your request has been noted and we will add such example soon in near future.
      So, keep visiting….

  3. This is a good tutorial.

    I’m not sure how far you’ll go with this example. Are you going to work with the DB here? If not, I don’t think SpringMVC is not the right tool because you have to open the Spring MVC documentation to do these boring things: 1) declare a Spring dispatcher servlet in web.xml 2) write a Spring xml configuration file with all the difficult-to-remember namespaces like mvc (for mvc:annotation-driven), context (for context:component-scan) 3) define the content negotiating view resovlver.

    I think a REST implementation like Jersey or RESTeasy are better for this example.

  4. Hi Sir Rahul,
    I’m very glad to found your website for learning.
    Can you please help me if you have any tutorials, for Spring MVC form binding and JQuery Ajax? I need to return a List of object to be populated on the table, then needs to submit it after editing of the List of Object data. Really would appreciate any help or if you can just lead me to the right direction or tutorial links. Thank you and more power.

  5. Many thanks, Rahul for all your post. Incredible useful as a very needed starting point. This and the last post worked also with jQuery 1.7.1, Spring MVC 3.1.1 and Jackson 1.9.6.
    Keep on.

  6. I run this example in Eclipse Indigo but not successful. There is an error when click [Add Users] button: error: [object XMLHttprequest]

  7. This is very good tutorial..
    appreciate your time for preparing this tutorial..

  8. Thanks for the interesting article. I kind of think of web design as landscaping your website. It was interesting to read your perspective on this. I enjoyed your post.

Leave a Comment Cancel reply


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