數據校驗在web應用里是非常重要的功能,尤其是在表單輸入中。在這里采用Hibernate-Vapdator進行校驗,該方法實現了JSR-303驗證框架支持注解風格的驗證。
一、導入jar包
若要實現數據校驗功能,需要導入必要的jar包,主要包括以下幾個:
classmate-1.3.1.jar
hibernate-vapdator-5.4.1.Final.jar
hibernate-vapdator-annotation-processor-5.4.1.Final.jar
hibernate-vapdator-cdi-5.4.1.Final.jar
jboss-logging-3.3.0.Final.jar
vapdation-api-1.1.0.Final.jar
二、常用的校驗注解
注解 | 功能 |
---|---|
@Null | 驗證對象是否為 null |
@NotNull | 驗證對象是否不為 null |
@AssertTrue | 驗證 Boolean 對象是否為 true |
@AssertTrue | 驗證 Boolean 對象是否為 false |
@Max(value) | 驗證 Number 和 String 對象是否小于等于指定值 |
@Min(value) | 驗證 Number 和 String 對象是否大于等于指定值 |
@DecimalMax(value) | 驗證注解的元素值小于等于 @DecimalMax 指定的 value 值 |
@DecimalMin(value) | 驗證注解的元素值大于等于 @DecimalMin 指定的 value 值 |
@Digits(integer,fraction) | 驗證字符串是否符合指定格式的數字,integer 指定整數精度,fraction 指定小數精度 |
@Size(min,max) | 驗證對象長度是否在給定的范圍內 |
@Past | 驗證 Date 和 Calendar 對象是否在當前時間之前 |
@Future | 驗證 Date 和 Calendar 對象是否在當前時間之后 |
@Pattern | 驗證 String 對象是否符合正則表達式的規則 |
@NotBlank | 檢查字符串是不是 Null,被 Trim 的長度是否大于0,只對字符串,且會去掉前后空格 |
@URL | 驗證是否是合法的 url |
驗證是否是合法的郵箱 | |
@CreditCardNumber | 驗證是否是合法的信用卡號 |
@Length(min,max) | 驗證字符串的長度必須在指定范圍內 |
@NotEmpty | 檢查元素是否為 Null 或 Empty |
@Range(min,max,message) | 驗證屬性值必須在合適的范圍內 |
三、修改實體類
在類的屬性上進行標注,如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class User { @NotBlank (message = "Username can not be empty" ) private String username; @NotBlank (message = "password can not be blank" ) @Length (min = 6 , max = 16 , message = "The length of the password must be between 6 and 16 bits" ) private String password; @Range (min = 18 , max = 60 , message = "Age must be between 18 and 60 years old" ) private Integer age; @Pattern (regexp = "^1[3|4|5|7|8][0-9]{9}$" , message = "Please enter the correct format of the phone number" ) private String phone; @Email (message = "Please enter a valid email address" ) private String email; // other... } |
四、修改相應的處理方法
1
2
3
4
5
6
7
8
|
@RequestMapping (value = "/register" ) public String register( @Valid @ModelAttribute ( "user" ) User user, Errors errors,Model model) { if (errors.hasErrors()){ return "register" ; } model.addAttribute( "user" , user); return "success" ; } |
五、視圖輸出
校驗之后,我們通常需要在表單的輸入框后進行文字反饋:
1
2
3
4
5
6
7
8
9
10
11
|
<form:form modelAttribute= "user" method= "post" action= "register" > <fieldset> <legend>register</legend> <p> <label>name:</label> <form:input path= "username" /> <form:errors path= "username" cssStyle= "color:red" /> </p> ... </fieldset> </form:form> |
然而,有些時候并不推薦直接將錯誤信息寫在注解的message屬性里,這樣不方便國際化。因此可以做以下幾處修改:
1. 新建validatemessages.properties
1
2
3
4
5
6
|
username.not.blank = "username cannot be empty..." password.not.blank = "password cannot be empty" password.not.length = "password should be in 6-10" age.not.range = "age should be in 10-70" phone.not.pattern = "phone should be in format" email.not.format = "email should be in format" |
2. 實體類中的注解使用相對引用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class User { @NotBlank (message = "{username.not.blank}" ) private String username; @NotBlank (message = "{password.not.blank}" ) @Length (min = 6 , max = 10 , message = "{password.not.length}" ) private String password; @Range (min = 10 , max = 70 , message = "{age.not.range}" ) private Integer age; @Pattern (regexp = "^1[3|4|5|7|8][0-9]{9}$" , message = "{phone.not.pattern}" ) private String phone; @Email (message = "{email.not.format}" ) private String email; // other... } |
3. 修改配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<!-- 默認的注解映射的支持 --> <mvc:annotation-driven validator= "validator" conversion-service= "conversion-service" /> <bean id= "validator" class = "org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" > <property name= "providerClass" value= "org.hibernate.validator.HibernateValidator" /> <!--不設置則默認為classpath下的 ValidationMessages.properties --> <property name= "validationMessageSource" ref= "validatemessageSource" /> </bean> <bean id= "conversion-service" class = "org.springframework.format.support.FormattingConversionServiceFactoryBean" /> <bean id= "validatemessageSource" class = "org.springframework.context.support.ReloadableResourceBundleMessageSource" > <property name= "basename" value= "classpath:validatemessages" /> <property name= "fileEncodings" value= "utf-8" /> <property name= "cacheSeconds" value= "120" /> </bean> |
特別注意:value="classpath:validatemessages",文件名不加后綴!
至此,數據校驗的整個過程就結束了。
最后還要特別強調的重點是:
視圖中<form:form modelAttribute="contentModel" method="post">的modelAttribute="xxx"后面的名稱xxx必須與對應的@Valid @ModelAttribute("xxx") 中的xxx名稱一致,否則模型數據和錯誤信息都綁定不到。
<form:errors path="name"></form:errors>即會顯示模型對應屬性的錯誤信息,當path="*"時則顯示模型全部屬性的錯誤信息。
以上這篇SpringMVC 數據校驗方法(必看篇)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。