Ajax with Spring MVC 3 using Annotations and JQuery

Its always been fun for me to work with Ajax! Is not it ? I will make it easy for you  to use Ajax with Spring MVC 3 and JQuery. This post will illustrate you how to use Ajax in real life practices of industrial coding. As usual, we will take an practical example of Ajax in Spring MVC 3 framework and will implement it and I will make the implementation easy by make you understand the topic.

Let us see what is our example’s requirement and how Spring MVC 3 Ajax facility will fulfill it :

In our example, we will make a list of students with name and highest education level, to send the list to the placement office so that the students can get chance. We will make the “Add Student Form” available to the student online so that they can submit their name online and get registered. As a lot of students will use the system, so the performance of the system may very much low. To increase to performance of the web application we will use Ajax with Spring MVC 3 Framework and JQuery.

Following steps we have to go through to implement our example :

  1. First of all, we will create a domain class (User.java) that will hold the value of student information.
  2. After that we will create our controller class (UserListController.java) to handle HTTP request. Our controller will handle three types of requests. First, to show the “Add Student Form”, second to handle Ajax request came from “Add Student Form” and add the students to a list, third to show the student information as a list.
  3. Then, we will create jsp page  (AddUser.jsp) to show “Add Student Form” that will use JQuery to send Ajax request to the Spring MVC Controller. The jsp will also confirm to the user that Student has been added to the list.
  4. Then, we will create a jsp (ShowUsers.jsp) that will list all users in the list.


User.java has two properties name and education to store the student information. Following is the code of User.java :

package com.raistudies.domain;

public class User {

    private String name = null;
    private String education = null;
    // Getter and Setter are omitted for making the code short


Controllers has three method to handle three request urls. “showForm” method handle the request for showing the form to the user. Bellow code shows the UserListController.java :

package com.raistudies.controllers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.raistudies.domain.User;

public class UserListController {
    private List<User> userList = new ArrayList<User>();

    public String showForm(){
        return "AddUser";

    public @ResponseBody String addUser(@ModelAttribute(value="user") User user, BindingResult result ){
        String returnText;
            returnText = "User has been added to the list. Total number of users are " + userList.size();
            returnText = "Sorry, an error has occur. User has not been added to list.";
        return returnText;

    public String showUsers(ModelMap model){
        model.addAttribute("Users", userList);
        return "ShowUsers";

“addUsers” is same as the controller method that handle form expect that it also contain annotation @ResponseBody, which tells Spring MVC that the String returned by the method is the response to the request, it does not have to find view for this string. So the retuning String will be send back to the browser as response and hence the Ajax request will work. “showUsers” method is used to show the list of the students to the user.


AddUser.jsp contain a simple form to collect information about the student and uses JQerey JavaScript framework to generate Ajax request to the server. Following is the code in AddUser.jsp :

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

        type: "POST",
        url: "/AjaxWithSpringMVC2Annotations/AddUser.htm",
        data: "name=" + name + "&education=" + education,
        success: function(response){
        // we have the response
        error: function(e){
        alert('Error: ' + e);
        <h1>Add Users using Ajax ........</h1>
            <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>
        <a href="/AjaxWithSpringMVC2Annotations/ShowUsers.htm">Show All Users</a>

You may be little bit confused if you are not aware of JQuery. Here is the explanation of the JQuery code :

  1. var name = $(‘#name’).val();  : -  here the $ is JQuery selector that uses to select any node in HTML whose identifier is passed as argument. If the identifier is a prefix with # that means it is a id of the HTML node. Here, $(‘#name’).val() contains the value of the HTML node whose is “name’. The text box in which user will enter her/his name is with is as name. so java script variable name will contain the name of the user.
  2. $.ajax() :- It is the method in $ variable of JQuery to call Ajax. It has five arguments here. First of all “type” which indicated the request type of Ajax. It can be POST or GET. Then, “url” which indicates the url to be hit of Ajax submission. “data” will contain the raw data to be sent to the server. “success” will contain the function code that has to be call if the request get success and server sends an response to the browser.  “error” will contain the function code that has to be call if the request get any error.
  3. $(‘#info’).html(response); :- will set the response of the server in to the div. In this way “Hello” + name will be shown in the div whose id is “info“.


Following are the code in ShowUsers.jsp to print all student information from a ArrayList to jsp page :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Users Added using Ajax</title>
    <body style="color: green;">
    The following are the users added in the list :<br>
            <c:forEach items="${Users}" var="user">
                <li>Name : <c:out value="${user.name}" />; Education : <c:out value="${user.education}"/>

Here, we have used JSTL core taglib to iterate through the ArrayList and show every value in browser.

  • <c:forEach items=”${Users}” var=”user”> : tag is used for iterate through the ArrayList. Property “items” is used to define the bean on which the List object has been stored, so items=”${Users}” says that the users list is present in “Users” bean. “var” attribute says the name of the variable in which each user will be stored.
  • <c:out value=”${user.name}” /> : As, a single user will be stored in variable name “user” so to print the name property in User object we use ${user.name}.

Our Spring MVC configuration file should be able to handle annotation driven controllers. The configuration are as follows :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.raistudies" />

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>


Deploy the war file to tomcat 6 and hit the url in browser, you will get following page displayed :

Ajax Form Using Spring MVC 3

Ajax Form Using Spring MVC 3

Fill student information :

Ajax Filled Form Using Spring MVC 3

Ajax Filled Form Using Spring MVC 3

After that click on “Add Users” button, you will get message that user has been added to the list :

Ajax Form Submission Confirmation

Ajax Form Submission Confirmation Spring MVC 3

To show all student added to the list click on the button “Show All Users”, you will get following page :

Show All Users Spring MVC 3

Show All Users Spring MVC 3

That is all from Ajax using Spring MVC 3 and JQuery. You can download source from bellow link.

Source : Download

War : Download

Related Posts:

Leave a comment ?


  1. Really good tutorial regarding using JQuery and Spring together

  2. Awesome things here. I am very glad to peer your post. Thank you so much and I’m having a look forward to touch you. Will you kindly drop me a e-mail?

  3. I will right away grab your rss as I can’t in finding your email subscription link or e-newsletter service. Do you’ve any? Kindly allow me realize so that I may subscribe. Thanks.

  4. It’s really a nice and helpful piece of information. I’m satisfied that you just shared this useful info with us. Please keep us up to date like this. Thanks for sharing.

  5. I do consider all the ideas you’ve offered on your post. They are very convincing and will certainly work. Nonetheless, the posts are too quick for starters. May just you please lengthen them a little from next time? Thanks for the post.

  6. Thanks a bunch for sharing this with all of us you really know what you’re talking about! Bookmarked.

  7. A person necessarily lend a hand to make critically posts I’d state. That is the very first time I frequented your website page and so far? I surprised with the analysis you made to make this actual submit incredible. Fantastic job!

  8. Hello there, just changed into aware of your weblog thru Google, and located that it’s truly informative. I am going to be careful for brussels. I’ll be grateful in the event you continue this in future. Many people will likely be benefited from your writing. Cheers!

  9. 😛
    excellent article..no words to describe…kudos to you..

  10. Great tutorial, but the download zip file was corrupted.

  11. Hi Rahul,
    i want to pass utf8 data in this example but not possible for me. output of this command in UserListController class is question sign(????…).
    i set Unicode to utf8 in all part such in ajax function and in jsp page and also in UserListController class.
    i modify this.

    in ajax function
    type: “POST”,
    url: contexPath + “/AddUser.htm”,
    contentType: “application/x-www-form-urlencoded;charset=UTF-8″,
    data: “name=” + name + “&education=” + education,
    in UserController
    public @ResponseBody JsonResponse addUser(@ModelAttribute(value=”user”) User user, BindingResult result,HttpServletRequest request, HttpServletResponse response ) throws UnsupportedEncodingException{
    and in jsp page change chrset to utf8

    but not correctly run.
    please help me.

  12. 😛 Thanks a lot!!!!!!!! much needed at this time

  13. I every time spеnt my half an hour tο read thіѕ website’s articles or reviews every day along with a mug of coffee.

  14. If in real world project each developers which wants ajax catability have to write this ugly javascript code…..

    In JSF 2 ajax is co simple

  15. Nice tutorial.I have once questions how can I define multiple controller?

  16. Keep this going please, great job!

  17. This blog was… how do I say it? Relevant!! Finally I have found something that helped me.

  18. I downloaded the source zip and the war zip. But I’m not able to open the zip files. I get error “start of central directory not found; Zip file corrupt. Possible cause: file transfer error”.

  19. Simple Yet powerful 😛

  20. Thanks for writing this information within your website.

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=""> <s> <strike> <strong>