Spring MVC 驗證主要還是用的是hibernate的驗證。so需要添加以下的jar包:
1、 hibernate-validator-5.2.2.Final.jar
2、hibernate-validator-annotation-processor-5.2.2.Final.jar (這個可以不用)
3、 log4j.jar
4 、slf4j-api-1.5.6.jar
5、 slf4j-log4j12-1.5.6.jar
6 、validation-api-1.1.0.Final.jar
以登錄驗證為例:
在實體屬性上配置注解;
package com.cy.springannotation.entity; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; /** * 定義一個表單實體類 * @author acer * */ public class UserBean { //要求屬性名必須要和表單的參數名一樣的! @NotEmpty(message="用戶名不能為空!") @Pattern(regexp="\\w{6,20}",message="用戶名6-20位") private String username; @NotEmpty(message="密碼不能為空") @Length(max=20,min=6,message="密碼不能小於6位") private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
JSP頁面上通過spring標記來獲取錯誤信息:
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 <!-- srpingmvc 驗證需要使用到spring表單標簽 --> 7 <%@ taglib prefix="springform" uri="http://www.springframework.org/tags/form" %> 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 9 <html> 10 <head> 11 <base href="<%=basePath%>"> 12 13 <title>驗證頁面</title> 14 15 <meta http-equiv="pragma" content="no-cache"> 16 <meta http-equiv="cache-control" content="no-cache"> 17 <meta http-equiv="expires" content="0"> 18 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 19 <meta http-equiv="description" content="This is my page"> 20 <!-- 21 <link rel="stylesheet" type="text/css" href="styles.css"> 22 --> 23 24 </head> 25 26 <body> 27 28 <!-- commandName用於指定活動的Bean對象,即我可以在頁面上,獲取對象屬性所對應的錯誤信息,值是對象名稱的首字母小寫,同modelAttribute一樣的意思(modelAttribute="contentModel") --> 29 <!-- <springform:form method="post" action="login.do" commandName="userBean"> --> 30 <springform:form method="post" action="login.do" modelAttribute="user"> 31 32 <table> 33 <tr> 34 <td>用戶名:</td> 35 <td><input type="text" name="username"/><springform:errors delimiter="," path="username"></springform:errors></td> 36 </tr> 37 <tr> 38 <td>密碼</td> 39 <td><input type="text" name="password"/><springform:errors delimiter="," path="password"></springform:errors></td> 40 </tr> 41 <tr> 42 <td colspan="2"> <input type="submit" value="提交"/> </td> 43 </tr> 44 </table> 45 </springform:form> 46 </body> 47 </html>
delimiter:如果一個屬性有多個錯誤,錯誤信息的分隔符。默認是換行.
path:驗證失敗的屬性名.
控制器:
1 @RequestMapping(value="/login.do") 2 //@Valid 通過該注解告知該方法,我的哪個實體Bean需要驗證 3 //BindingResult 為固定參數,用於接收驗證結果 4 5 public String login(@ModelAttribute("user") @Valid UserBean user,BindingResult br) { 6 if(br.hasErrors()){ 7 //驗證未通過則 8 return "validate1"; 9 } 10 log.info(user.getUsername()); 11 log.info(user.getPassword()); 12 13 return "index"; 14 }
如果界面上使用了spring標簽,那么需要預先啟動Spring容器,所以在web.xml中增加配置:
1 <!-- 啟動spring容器,用於支持springmvc validate --> 2 <context-param> 3 <param-name>contextConfigLocation</param-name> 4 <param-value>/WEB-INF/classes/springAnnotation-servlet.xml</param-value> 5 </context-param> 6 7 <!-- 配置在context-param里面文件內的內容,需要通過 ContextLoaderListener添加到上下文里面去--> 8 <listener> 9 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 10 </listener>
到springAnnotation-servlet.xml文件中配置:
1 <!-- 開啟注解這里需要添加個validator--> 2 <!--開啟注解 --> 3 <mvc:annotation-driven conversion-service="tc" validator="validator" /> 4 5 <!-- 驗證配置,告知srpingmvc,我使用的是Hibernate驗證框架來完成的驗證 --> 6 <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 7 <property name="providerClass" value="org.hibernate.validator.HibernateValidator" /> 8 </bean>
顯示測試:
進入登錄頁面
直接點擊提交:
下面是主要的驗證注解及說明:
注解 |
適用的數據類型 |
說明 |
@AssertFalse |
Boolean, boolean |
驗證注解的元素值是false |
@AssertTrue |
Boolean, boolean |
驗證注解的元素值是true |
@DecimalMax(value=x) |
BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence. |
驗證注解的元素值小於等於@ DecimalMax指定的value值 |
@DecimalMin(value=x) |
BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence. |
驗證注解的元素值小於等於@ DecimalMin指定的value值 |
@Digits(integer=整數位數, fraction=小數位數) |
BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence. |
驗證注解的元素值的整數位數和小數位數上限 |
@Future |
java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant. |
驗證注解的元素值(日期類型)比當前時間晚 |
@Max(value=x) |
BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number. |
驗證注解的元素值小於等於@Max指定的value值 |
@Min(value=x) |
BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number. |
驗證注解的元素值大於等於@Min指定的value值 |
@NotNull |
Any type |
驗證注解的元素值不是null |
@Null |
Any type |
驗證注解的元素值是null |
@Past |
java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant. |
驗證注解的元素值(日期類型)比當前時間早 |
@Pattern(regex=正則表達式, flag=) |
String. Additionally supported by HV: any sub-type of CharSequence. |
驗證注解的元素值與指定的正則表達式匹配 |
@Size(min=最小值, max=最大值) |
String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence. |
驗證注解的元素值的在min和max(包含)指定區間之內,如字符長度、集合大小 |
@Valid |
Any non-primitive type(引用類型) |
驗證關聯的對象,如賬戶對象里有一個訂單對象,指定驗證訂單對象 |
@NotEmpty |
|
驗證注解的元素值不為null且不為空(字符串長度不為0、集合大小不為0) |
@Range(min=最小值, max=最大值) |
|
驗證注解的元素值在最小值和最大值之間 |
@NotBlank |
|
驗證注解的元素值不為空(不為null、去除首位空格后長度為0),不同於@NotEmpty,@NotBlank只應用於字符串且在比較時會去除字符串的空格 |
@Length(min=下限, max=上限) |
|
驗證注解的元素值長度在min和max區間內 |
|
|
驗證注解的元素值是Email,也可以通過正則表達式和flag指定自定義的email格式 |