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 :
- First of all, we will create a domain class (User.java) that will hold the value of student information.
- 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.
- 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.
- Then, we will create a jsp (ShowUsers.jsp) that will list all users in the list.
User.java
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 }
UserListController.java
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; @Controller public class UserListController { private List<User> userList = new ArrayList<User>(); @RequestMapping(value="/AddUser.htm",method=RequestMethod.GET) public String showForm(){ return "AddUser"; } @RequestMapping(value="/AddUser.htm",method=RequestMethod.POST) public @ResponseBody String addUser(@ModelAttribute(value="user") User user, BindingResult result ){ String returnText; if(!result.hasErrors()){ userList.add(user); returnText = "User has been added to the list. Total number of users are " + userList.size(); }else{ returnText = "Sorry, an error has occur. User has not been added to list."; } return returnText; } @RequestMapping(value="/ShowUsers.htm") 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
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 Add>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(); $.ajax({ type: "POST", url: "/AjaxWithSpringMVC2Annotations/AddUser.htm", data: "name=" + 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="/AjaxWithSpringMVC2Annotations/ShowUsers.htm">Show All Users</a> </body> </html>
You may be little bit confused if you are not aware of JQuery. Here is the explanation of the JQuery code :
- 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.
- $.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.
- $(‘#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“.
ShowUsers.jsp
Following are the code in ShowUsers.jsp to print all student information from a ArrayList to jsp page :
<%@>Users Added using Ajax</title> </head> <body style="color: green;"> The following are the users added in the list :<br> <ul> <c:forEach <li>Name : <c:out; Education : <c:out </c:forEach> </ul> </body> </html>
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}.
app-config.xml
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="" xmlns: <!-- Scans the classpath of this application for @Components to deploy as beans --> <context:component-scan <!-- 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"/> </bean> </beans>
Deploy the war file to tomcat 6 and hit the url in browser, you will get following page displayed :
Fill student information :
After that click on “Add Users” button, you will get message that user has been added to the list :
To show all student added to the list click on the button “Show All Users”, you will get following page :
That is all from Ajax using Spring MVC 3 and JQuery. You can download source from bellow link.
Source : Download
Reference: Ajax with Spring MVC 3 using Annotations and JQuery from our JCG partner Rahul Mondal at the Rai Studies blog.
I would recommend always returning public atResponseBoy Map (The form replaces the at symbol automatically through some Twitter parser)so that you have more flexibility in the result and define some standard keys in this response for Forms that you can code against in the frontend, such as an errors key, which will contain the binding result errors. and have some kind of general error handler that you but in a BaseController class that you extend. This will prevent stacktraces from showing up in your json messages. atExceptionHandler(Exception.class) public atResponseBody Map handleException(Exception e, HttpServletRequest request, HttpServletResponse response) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); Map errors = new… Read more »
There should also be an emphasis on a sound domain model. Do you really want a User class to hold Student information? A student can be a user, but not all users are students..
it is not working in IE8..
Thanks, nice tips
Nice tutorial
Plz tell me what’s wrong in this code:——– —————– IN JSP PAGE:—-trying to passsing req to code… $(“#id_complaint”).change(function(){ var v_ttType = $(“#id_complaint”).val(); alert(v_ttType); $.getJSON(“./attributeListcreateTT.*”,{TTType:v_ttType,ajax:’true’}, function(resp) { alert(‘in json’); for(var i=0;i<resp.length;i++) { alert(resp[i].ATTRIBUTE); alert(resp[i].OUTCOME); } }); }); }); /———-in java public String attributeList() { //templist2=(ArrayList)CnmRefData.getTTAttributes(prod, ttType); //return templist2; System.out.println("in attributeList………………RequestCAme…."); try{ JSONObject object = null; JSONArray array = null; List jsonAttrList = new ArrayList(); String ttType = httpServletRequest.getParameter(“TTType”); System.out.println(“In *>>> ::”+ttType); templist2=(ArrayList)CnmRefData.getTTAttributes(“RON”, ttType); System.out.println(“::::”+templist2.size()); Iterator itr = templist2.iterator(); while(itr.hasNext()){ CNMTTAttribute objCNMTTAttribute = (CNMTTAttribute)itr.next(); object = new JSONObject(); object.put(“ATTRIBUTE”, objCNMTTAttribute.getAttribute()); object.put(“OUTCOME”,objCNMTTAttribute.getValidateOutcome()); jsonAttrList.add(object); } array = JSONArray.fromObject(jsonAttrList); response.setHeader(“Cache-Control”,”no-cache”); response.getWriter().write(array.toString()); }catch(NullPointerException e){ addActionError(e.getMessage()); e.printStackTrace();… Read more »
Hi, Good example with nice explaination.Thx
I am a beginner in spring…can you tell me what are the jar file required for this
how to send spring controller java object to html using js, ajax and knouckout js.
spring controller return model with attribute like jsp but instead of jsp i want to use html.