Spring MVC和JQuery用于Ajax表单验证

在本教程中,我们将看到如何使用Ajax和Spring MVCJQuery在服务器端验证表单。 Spring MVC为通过注释驱动的配置采用Ajax提供了非常方便的过程。 我们将使用此注释驱动的配置以JSON数据的形式发送Ajax响应。 响应将包含表单验证的状态,并且表单数据中存在任何错误的错误消息。

使用的工具:
  • Spring MVC 3.0.3
  • jQuery 1.4.2
  • 杰克逊1.5.3
在示例中,我们将使用Ajax和Spring MVC将具有名称和教育程度的用户添加到列表中。 用户数据将在JQuery的帮助下发送到Spring MVC控制器,并且如果表单数据中没有验证错误,控制器将返回添加的用户的完整列表,直到时间为止;如果表单数据中存在验证错误,则控制器将返回验证错误。 。
因此,我们将在本教程中学习两个重要的知识:
  1. 如何在JQuery的帮助下在Spring MVC中使用Ajax验证表单数据?
  2. 以及如何将对象列表发回给Ajax调用作为响应?
用户的域类
以下是我们的User域类,它将保存表单数据:
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;
        }

}
showForm()用于将“添加”用户表单添加到浏览器。 方法addUser()将处理ajax请求并验证User对象,如果表单数据中没有验证错误,它将把userList对象设置为JsonResponse类的result属性,状态为“ SUCCESS ”。 但是,如果表单数据中存在错误, 它将使用getAllErrors()方法从BindingResult对象中提取错误列表,并将其设置为状态为“ FAIL ”的JsonResponse类的result属性。
AddUser.jsp
以下是在JQuery的帮助下使用Ajax调用UserController的jsp页面:
<%@ 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值