使用的工具:
- 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 values
var 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 response
if(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