javascript
Spring MVC表单验证(带批注)
這篇文章提供了一個(gè)簡(jiǎn)單HTML表單驗(yàn)證示例。 它基于帶有注釋的Spring MVC示例。 該代碼可在GitHub的Spring-MVC-Form-Validation目錄中找到。
數(shù)據(jù)
在此示例中,我們將使用bean和JSR303驗(yàn)證批注:
頁(yè)數(shù)
我們的表單將包含輸入元素,但也可能顯示錯(cuò)誤消息:
<%@page contentType='text/html' pageEncoding='UTF-8'%> <%@ taglib prefix='form' uri='http://www.springframework.org/tags/form' %> <!doctype html> <html> <head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><title>My User Form!</title> </head> <body><form:form method='post' action='myForm' commandName='myUser'><table><tr><td>Name: <font color='red'><form:errors path='name' /></font></td></tr><tr><td><form:input path='name' /></td></tr><tr><td>Age: <font color='red'><form:errors path='age' /></font></td></tr><tr><td><form:input path='age' /></td></tr><tr><td><input type='submit' value='Submit' /></td></tr></table></form:form> </body> </html>我們的成功頁(yè)面是:
<%@page contentType='text/html' pageEncoding='UTF-8'%> <%@taglib prefix='form' uri='http://www.springframework.org/tags/form'%> <%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %> <!doctype html> <html> <head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><title>Form Processed Successfully!</title> </head> <body>Form processed for <c:out value='${myUser.name}' /> ! <br /><a href='<c:url value='/'/>'>Home</a> </body> </html>我們的主頁(yè):
<%@page contentType='text/html' pageEncoding='UTF-8'%> <%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %> <!doctype html> <html lang='en'> <head><meta charset='utf-8'><title>Welcome !!!</title> </head> <body><h1>Spring Form Validation !!!</h1> <a href='<c:url value='/myForm'/>'>Go to the form!</a> </body> </html>
控制者
注意,我們需要使用
@ModelAttribute確保一個(gè)實(shí)例
MyUser在模型中始終可用。 在里面 validateForm(),我們需要使用 @ModelAttribute將表單內(nèi)容移動(dòng)到 MyUser項(xiàng)目。
Maven依賴(lài)
我們需要以下依賴(lài)關(guān)系。 Hibernate驗(yàn)證程序依賴(lài)項(xiàng)對(duì)于處理JSR303批注是必需的:
<dependency><groupId>javax.validation</groupId><artifactId>validation-api</artifactId><version>1.0.0.GA</version><type>jar</type> </dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>4.3.0.Final</version> </dependency>
運(yùn)行示例
編譯后,該示例可以與
mvn tomcat:運(yùn)行。 然后,瀏覽:
http:// localhost:8383 // spring-mvc-form-validation /。
如果最終用戶(hù)輸入無(wú)效的值,將顯示錯(cuò)誤消息:
參考: 技術(shù)說(shuō)明博客上的JCG合作伙伴 Jerome Versrynge提供的Spring MVC表單驗(yàn)證(帶有批注) 。
翻譯自: https://www.javacodegeeks.com/2012/10/spring-mvc-form-validation-with-annotations.html
總結(jié)
以上是生活随笔為你收集整理的Spring MVC表单验证(带批注)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 多玩app下载(多玩安卓版)
- 下一篇: Spring Security可以做的十