使用的工具:
- Spring MVC 3.0.3
- jQuery 1.4.2
- 杰克遜1.5.3
- 如何在JQuery的幫助下在Spring MVC中使用Ajax驗證表單數據?
- 以及如何將對象列表發回給Ajax調用作為響應?
package com.raistudies.domain;public class User {private String name = null;private String education = null;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getEducation() {return education;}public void setEducation(String education) {this.education = education;}}
我們的用戶域對象名稱和教育有兩個字段。
用于發送JSON響應的Ajax響應域類
以下是我們將用于發送響應的域對象:
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;}}
它包含兩個屬性,“狀態”和“結果”。 “狀態”字段是字符串類型,將包含“失敗”或“成功”。 “結果”將包含其他要發送回瀏覽器的數據。
UserController.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.validation.ValidationUtils;
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.JsonResponse;
import com.raistudies.domain.User;@Controller
public class UserController {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 JsonResponse addUser(@ModelAttribute(value="user") User user, BindingResult result ){JsonResponse res = new JsonResponse();ValidationUtils.rejectIfEmpty(result, "name", "Name can not be empty.");ValidationUtils.rejectIfEmpty(result, "education", "Educatioan not be empty");if(!result.hasErrors()){userList.add(user);res.setStatus("SUCCESS");res.setResult(userList);}else{res.setStatus("FAIL");res.setResult(result.getAllErrors());}return res;}}
<%@ 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="<%=request.getContextPath() %>/js/jquery.js"></script>
<script type="text/javascript">var contexPath = "<%=request.getContextPath() %>";
</script>
<script src="<%=request.getContextPath() %>/js/user.js"></script>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/style/app.css">
</head>
<body>
<h1>Add Users using Ajax ........</h1><table><tr><td colspan="2"><div id="error" class="error"></div></td></tr><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" class="success"></div></td></tr></table>
</body>
</html>
該jsp頁面包含一個js文件user.js ,該文件已用于保存JavaScript方法doAjaxPost()的定義,該方法生成ajax類,并且還使用Ajax調用的響應來動態更新頁面數據。
user.js
以下是ajax類的代碼,并解釋了從Spring MVC控制器收到的響應:
function doAjaxPost() {// get the form valuesvar name = $('#name').val();var education = $('#education').val();$.ajax({type: "POST",url: contexPath + "/AddUser.htm",data: "name=" + name + "&education=" + education,success: function(response){// we have the responseif(response.status == "SUCCESS"){userInfo = "<ol>";for(i =0 ; i < response.result.length ; i++){userInfo += "<br><li><b>Name</b> : " + response.result[i].name +";<b> Education</b> : " + response.result[i].education;}userInfo += "</ol>";$('#info').html("User has been added to the list successfully. " + userInfo);$('#name').val('');$('#education').val('');$('#error').hide('slow');$('#info').show('slow');}else{errorInfo = "";for(i =0 ; i < response.result.length ; i++){errorInfo += "<br>" + (i + 1) +". " + response.result[i].code;}$('#error').html("Please correct following errors: " + errorInfo);$('#info').hide('slow');$('#error').show('slow');}},error: function(e){alert('Error: ' + e);}});
}
JQuery的$ .ajax()方法已用于在此處進行Ajax調用,該調用將表單數據名稱和教育字段值發送給Spring Controller。 在Ajax調用成功后,它首先檢查響應的狀態字段。 請注意,此處的響應對象是JsonResponse Java對象的JSON表示形式。
如果響應的狀態字段為“ SUCCESS”,則使用符號response.result [i]遍歷用戶列表,請注意,杰克遜庫將Java的列表對象轉換為json數組。
如果狀態為“ FAIL”,則結果對象將包含驗證錯誤,我們可以使用符號response.result [i] .code進行訪問 ,此處代碼將返回在Spring控制器中添加的錯誤消息。 在tomcat 6服務器上運行示例時,它將打開以下形式:
![]() |
Ajax驗證表 |
只需單擊“添加用戶”按鈕而不輸入任何值,它將顯示該字段的錯誤,如下圖所示:
![]() |
頁面中的Ajax驗證顯示錯誤 |
現在輸入任何名稱和學歷,然后單擊“添加用戶”按鈕。 它將在列表中添加用戶詳細信息,并在頁面上顯示整個用戶列表的信息:
![]() |
使用Spring MVC和JQuery成功頁面進行Ajax驗證 |
您也可以通過從以下鏈接下載示例來嘗試該示例:
資料來源: 下載
來源+庫: 下載
參考:我們的JCG合作伙伴 使用Spring MVC和JQuery進行Ajax表單驗證 ? Rai Studies博客上的Rahul Mondal。
翻譯自: https://www.javacodegeeks.com/2012/02/spring-mvc-and-jquery-for-ajax-form.html