日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring MVC和JQuery用于Ajax表单验证

發(fā)布時間:2023/12/3 javascript 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring MVC和JQuery用于Ajax表单验证 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在本教程中,我們將看到如何使用Ajax和Spring MVC和JQuery在服務器端驗證表單。 Spring MVC為通過注釋驅動的配置采用Ajax提供了非常方便的過程。 我們將使用此注釋驅動的配置以JSON數(shù)據(jù)的形式發(fā)送Ajax響應。 響應將包含表單驗證的狀態(tài),并且表單數(shù)據(jù)中存在任何錯誤的錯誤消息。

使用的工具:
  • Spring MVC 3.0.3
  • jQuery 1.4.2
  • 杰克遜1.5.3
在示例中,我們將使用Ajax和Spring MVC將具有名稱和教育程度的用戶添加到列表中。 用戶數(shù)據(jù)將在JQuery的幫助下發(fā)送到Spring MVC控制器,并且如果表單數(shù)據(jù)中沒有驗證錯誤,控制器將返回添加的用戶的完整列表,直到時間為止;如果表單數(shù)據(jù)中存在驗證錯誤,則控制器將返回驗證錯誤。 。 因此,我們將在本教程中學習兩個重要的知識:
  • 如何在JQuery的幫助下在Spring MVC中使用Ajax驗證表單數(shù)據(jù)?
  • 以及如何將對象列表發(fā)回給Ajax調用作為響應?
  • 用戶的域類 以下是我們的User域類,它將保存表單數(shù)據(jù): 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;}}

    我們的用戶域對象名稱和教育有兩個字段。
    用于發(fā)送JSON響應的Ajax響應域類
    以下是我們將用于發(fā)送響應的域對象:

    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;}}

    它包含兩個屬性,“狀態(tài)”和“結果”。 “狀態(tài)”字段是字符串類型,將包含“失敗”或“成功”。 “結果”將包含其他要發(fā)送回瀏覽器的數(shù)據(jù)。
    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對象,如果表單數(shù)據(jù)中沒有驗證錯誤,它將把userList對象設置為JsonResponse類的result屬性,狀態(tài)為“ SUCCESS ”。 但是,如果表單數(shù)據(jù)中存在錯誤, 它將使用getAllErrors()方法從BindingResult對象中提取錯誤列表,并將其設置為狀態(tài)為“ 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調用的響應來動態(tài)更新頁面數(shù)據(jù)。
    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調用,該調用將表單數(shù)據(jù)名稱和教育字段值發(fā)送給Spring Controller。 在Ajax調用成功后,它首先檢查響應的狀態(tài)字段。 請注意,此處的響應對象是JsonResponse Java對象的JSON表示形式。
    如果響應的狀態(tài)字段為“ SUCCESS”,則使用符號response.result [i]遍歷用戶列表,請注意,杰克遜庫將Java的列表對象轉換為json數(shù)組。
    如果狀態(tài)為“ FAIL”,則結果對象將包含驗證錯誤,我們可以使用符號response.result [i] .code進行訪問 ,此處代碼將返回在Spring控制器中添加的錯誤消息。 在tomcat 6服務器上運行示例時,它將打開以下形式:

    Ajax驗證表

    只需單擊“添加用戶”按鈕而不輸入任何值,它將顯示該字段的錯誤,如下圖所示:

    頁面中的Ajax驗證顯示錯誤

    現(xiàn)在輸入任何名稱和學歷,然后單擊“添加用戶”按鈕。 它將在列表中添加用戶詳細信息,并在頁面上顯示整個用戶列表的信息:

    使用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

    總結

    以上是生活随笔為你收集整理的Spring MVC和JQuery用于Ajax表单验证的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。