Spring4新特性——集成Bean Validation 1.1(JSR-349)到SpringMVC

http://sishuok.com/forum/blogPost/list/7798.html


在之前的《跟我學SpringMVC》中的《第七章 註解式控制器的數據驗證、類型轉換及格式化》中已經介紹過SpringMVC集成Bean Validation 1.0(JSR-303),目前Bean Validation最新版本是Bean Validation 1.1(JSR-349),新特性可以到官網查看,筆者最喜歡的兩個特性是:跨參數驗證(比如密碼和確認密碼的驗證)和支持在消息中使用EL表達式,其他的還有如方法參數/返回值驗證、CDI和依賴注入、分組轉換等。對於方法參數/返回值驗證,大家可以參閱《Spring3.1 對Bean Validation規範的新支持(方法級別驗證) 》。

 

Bean Validation 1.1當前實現是Hibernate validator 5,且spring4才支持。接下來我們從以下幾個方法講解Bean Validation 1.1,當然不一定是新特性:

  1.  集成Bean Validation 1.1到SpringMVC
  2.  分組驗證及分組順序
  3.  消息中使用EL表達式
  4.  方法參數/返回值驗證
  5.  自定義驗證規則
  6.  類級別驗證器
  7.  腳本驗證器
  8.  cross-parameter,跨參數驗證
  9. 混合類級別驗證器和跨參數驗證器

因爲大多數時候驗證都配合web框架使用,而且很多朋友都諮詢過如分組/跨參數驗證,所以本文介紹下這些,且是和SpringMVC框架集成的例子,其他使用方式(比如集成到JPA中)可以參考其官方文檔:

規範:http://beanvalidation.org/1.1/spec/

hibernate validator文檔:http://hibernate.org/validator/ 

 

 1、集成Bean Validation 1.1到SpringMVC

1.1、項目搭建

首先添加hibernate validator 5依賴:

  1. <dependency>  
  2.     <groupId>org.hibernate</groupId>  
  3.     <artifactId>hibernate-validator</artifactId>  
  4.     <version>5.0.2.Final</version>  
  5. </dependency>  

如果想在消息中使用EL表達式,請確保EL表達式版本是 2.2或以上,如使用Tomcat6,請到Tomcat7中拷貝相應的EL jar包到Tomcat6中。

  1. <dependency>  
  2.     <groupId>javax.el</groupId>  
  3.     <artifactId>javax.el-api</artifactId>  
  4.     <version>2.2.4</version>  
  5.     <scope>provided</scope>  
  6. </dependency>  

請確保您使用的Web容器有相應版本的el jar包。

 

對於其他POM依賴請下載附件中的項目參考。

 

1.2、Spring MVC配置文件(spring-mvc.xml):

  1. <!-- 指定自己定義的validator -->  
  2. <mvc:annotation-driven validator="validator"/>  
  3.   
  4. <!-- 以下 validator  ConversionService 在使用 mvc:annotation-driven 會 自動註冊-->  
  5. <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">  
  6.     <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>  
  7.     <!-- 如果不加默認到 使用classpath下的 ValidationMessages.properties -->  
  8.     <property name="validationMessageSource" ref="messageSource"/>  
  9. </bean>  
  10.   
  11. <!-- 國際化的消息資源文件(本系統中主要用於顯示/錯誤消息定製) -->  
  12. <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
  13.     <property name="basenames">  
  14.         <list>  
  15.             <!-- 在web環境中一定要定位到classpath 否則默認到當前web應用下找  -->  
  16.             <value>classpath:messages</value>  
  17.             <value>classpath:org/hibernate/validator/ValidationMessages</value>  
  18.         </list>  
  19.     </property>  
  20.     <property name="useCodeAsDefaultMessage" value="false"/>  
  21.     <property name="defaultEncoding" value="UTF-8"/>  
  22.     <property name="cacheSeconds" value="60"/>  
  23. </bean>  

此處主要把bean validation的消息查找委託給spring的messageSource。

 

1.3、實體驗證註解:

  1. public class User implements Serializable {  
  2.     @NotNull(message = "{user.id.null}")  
  3.     private Long id;  
  4.   
  5.     @NotEmpty(message = "{user.name.null}")  
  6.     @Length(min = 5, max = 20, message = "{user.name.length.illegal}")  
  7.     @Pattern(regexp = "[a-zA-Z]{5,20}", message = "{user.name.illegal}")  
  8.     private String name;  
  9.   
  10.     @NotNull(message = "{user.password.null}")  
  11.     private String password;  
  12. }  

對於驗證規則可以參考官方文檔,或者《第七章 註解式控制器的數據驗證、類型轉換及格式化》。

 

1.4、錯誤消息文件messages.properties:

  1. user.id.null=用戶編號不能爲空  
  2. user.name.null=用戶名不能爲空  
  3. user.name.length.illegal=用戶名長度必須在520之間  
  4. user.name.illegal=用戶名必須是字母  
  5. user.password.null=密碼不能爲空  

 

1.5、控制器

  1. @Controller  
  2. public class UserController {  
  3.   
  4.     @RequestMapping("/save")  
  5.     public String save(@Valid User user, BindingResult result) {  
  6.         if(result.hasErrors()) {  
  7.             return "error";  
  8.         }  
  9.         return "success";  
  10.     }  
  11. }  

 

1.6、錯誤頁面:

  1. <spring:hasBindErrors name="user">  
  2.     <c:if test="${errors.fieldErrorCount > 0}">  
  3.         字段錯誤:<br/>  
  4.         <c:forEach items="${errors.fieldErrors}" var="error">  
  5.             <spring:message var="message" code="${error.code}" arguments="${error.arguments}" text="${error.defaultMessage}"/>  
  6.             ${error.field}------${message}<br/>  
  7.         </c:forEach>  
  8.     </c:if>  
  9.   
  10.     <c:if test="${errors.globalErrorCount > 0}">  
  11.         全局錯誤:<br/>  
  12.         <c:forEach items="${errors.globalErrors}" var="error">  
  13.             <spring:message var="message" code="${error.code}" arguments="${error.arguments}" text="${error.defaultMessage}"/>  
  14.             <c:if test="${not empty message}">  
  15.                 ${message}<br/>  
  16.             </c:if>  
  17.         </c:forEach>  
  18.     </c:if>  
  19. </spring:hasBindErrors>  

 

大家以後可以根據這個做通用的錯誤消息顯示規則。比如我前端頁面使用validationEngine顯示錯誤消息,那麼我可以定義一個tag來通用化錯誤消息的顯示:showFieldError.tag。  

 

1.7、測試

輸入如:http://localhost:9080/spring4/save?name=123 , 我們得到如下錯誤:

  1. name------用戶名必須是字母  
  2. name------用戶名長度必須在520之間  
  3. password------密碼不能爲空  
  4. id------用戶編號不能爲空  

 

基本的集成就完成了。

 

如上測試有幾個小問題:

1、錯誤消息順序,大家可以看到name的錯誤消息順序不是按照書寫順序的,即不確定;

2、我想顯示如:用戶名【zhangsan】必須在5到20之間;其中我們想動態顯示:用戶名、min,max;而不是寫死了;

3、我想在修改的時候只驗證用戶名,其他的不驗證怎麼辦。

接下來我們挨着試試吧。

 

2、分組驗證及分組順序

如果我們想在新增的情況驗證id和name,而修改的情況驗證name和password,怎麼辦? 那麼就需要分組了。

首先定義分組接口:

  1. public interface First {  
  2. }  
  3.   
  4. public interface Second {  
  5. }  

分組接口就是兩個普通的接口,用於標識,類似於java.io.Serializable。

 

接着我們使用分組接口標識實體:

  1. public class User implements Serializable {  
  2.   
  3.     @NotNull(message = "{user.id.null}", groups = {First.class})  
  4.     private Long id;  
  5.   
  6.     @Length(min = 5, max = 20, message = "{user.name.length.illegal}", groups = {Second.class})  
  7.     @Pattern(regexp = "[a-zA-Z]{5,20}", message = "{user.name.illegal}", groups = {Second.class})  
  8.     private String name;  
  9.   
  10.     @NotNull(message = "{user.password.null}", groups = {First.class, Second.class})  
  11.     private String password;  
  12. }  

 

驗證時使用如:

  1. @RequestMapping("/save")  
  2. public String save(@Validated({Second.class}) User user, BindingResult result) {  
  3.     if(result.hasErrors()) {  
  4.         return "error";  
  5.     }  
  6.     return "success";  
  7. }  

即通過@Validate註解標識要驗證的分組;如果要驗證兩個的話,可以這樣@Validated({First.class, Second.class})。

 

接下來我們來看看通過分組來指定順序;還記得之前的錯誤消息嗎? user.name會顯示兩個錯誤消息,而且順序不確定;如果我們先驗證一個消息;如果不通過再驗證另一個怎麼辦?可以通過@GroupSequence指定分組驗證順序:

 

  1. @GroupSequence({First.class, Second.class, User.class})  
  2. public class User implements Serializable {  
  3.     private Long id;  
  4.   
  5.     @Length(min = 5, max = 20, message = "{user.name.length.illegal}", groups = {First.class})  
  6.     @Pattern(regexp = "[a-zA-Z]{5,20}", message = "{user.name.illegal}", groups = {Second.class})  
  7.     private String name;  
  8.       
  9.     private String password;  
  10. }  

通過@GroupSequence指定驗證順序:先驗證First分組,如果有錯誤立即返回而不會驗證Second分組,接着如果First分組驗證通過了,那麼纔去驗證Second分組,最後指定User.class表示那些沒有分組的在最後。這樣我們就可以實現按順序驗證分組了。

 

3、消息中使用EL表達式

假設我們需要顯示如:用戶名[NAME]長度必須在[MIN]到[MAX]之間,此處大家可以看到,我們不想把一些數據寫死,如NAME、MIN、MAX;此時我們可以使用EL表達式。

 

如:

  1. @Length(min = 5, max = 20, message = "{user.name.length.illegal}", groups = {First.class})  

錯誤消息:

  1. user.name.length.illegal=用戶名長度必須在{min}到{max}之間  

 

其中我們可以使用{驗證註解的屬性}得到這些值;如{min}得到@Length中的min值;其他的也是類似的。

 

到此,我們還是無法得到出錯的那個輸入值,如name=zhangsan。此時就需要EL表達式的支持,首先確定引入EL jar包且版本正確。然後使用如:

  1. user.name.length.illegal=用戶名[${validatedValue}]長度必須在520之間  

使用如EL表達式:${validatedValue}得到輸入的值,如zhangsan。當然我們還可以使用如${min > 1 ? '大於1' : '小於等於1'},及在EL表達式中也能拿到如@Length的min等數據。

 

另外我們還可以拿到一個java.util.Formatter類型的formatter變量進行格式化:

  1. ${formatter.format("%04d", min)}  

 

4、方法參數/返回值驗證

這個可以參考《Spring3.1 對Bean Validation規範的新支持(方法級別驗證) 》,概念是類似的,具體可以參考Bean Validation 文檔。

 

5、自定義驗證規則

有時候默認的規則可能還不夠,有時候還需要自定義規則,比如屏蔽關鍵詞驗證是非常常見的一個功能,比如在發帖時帖子中不允許出現admin等關鍵詞。

 

1、定義驗證註解

  1. package com.sishuok.spring4.validator;  
  2.   
  3. import javax.validation.Constraint;  
  4. import javax.validation.Payload;  
  5. import java.lang.annotation.Documented;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.Target;  
  8. import static java.lang.annotation.ElementType.*;  
  9. import static java.lang.annotation.RetentionPolicy.*;  
  10. /** 
  11.  * <p>User: Zhang Kaitao 
  12.  * <p>Date: 13-12-15 
  13.  * <p>Version: 1.0 
  14.  */  
  15.   
  16. @Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })  
  17. @Retention(RUNTIME)  
  18. //指定驗證器  
  19. @Constraint(validatedBy = ForbiddenValidator.class)  
  20. @Documented  
  21. public @interface Forbidden {  
  22.   
  23.     //默認錯誤消息  
  24.     String message() default "{forbidden.word}";  
  25.   
  26.     //分組  
  27.     Class<?>[] groups() default { };  
  28.   
  29.     //負載  
  30.     Class<? extends Payload>[] payload() default { };  
  31.   
  32.     //指定多個時使用  
  33.     @Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })  
  34.     @Retention(RUNTIME)  
  35.     @Documented  
  36.     @interface List {  
  37.         Forbidden[] value();  
  38.     }  
  39. }  

 

2、 定義驗證器

  1. package com.sishuok.spring4.validator;  
  2.   
  3. import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.context.ApplicationContext;  
  6. import org.springframework.util.StringUtils;  
  7.   
  8. import javax.validation.ConstraintValidator;  
  9. import javax.validation.ConstraintValidatorContext;  
  10. import java.io.Serializable;  
  11.   
  12. /** 
  13.  * <p>User: Zhang Kaitao 
  14.  * <p>Date: 13-12-15 
  15.  * <p>Version: 1.0 
  16.  */  
  17. public class ForbiddenValidator implements ConstraintValidator<Forbidden, String> {  
  18.   
  19.     private String[] forbiddenWords = {"admin"};  
  20.   
  21.     @Override  
  22.     public void initialize(Forbidden constraintAnnotation) {  
  23.         //初始化,得到註解數據  
  24.     }  
  25.   
  26.     @Override  
  27.     public boolean isValid(String value, ConstraintValidatorContext context) {  
  28.         if(StringUtils.isEmpty(value)) {  
  29.             return true;  
  30.         }  
  31.   
  32.         for(String word : forbiddenWords) {  
  33.             if(value.contains(word)) {  
  34.                 return false;//驗證失敗  
  35.             }  
  36.         }  
  37.         return true;  
  38.     }  
  39. }  

 驗證器中可以使用spring的依賴注入,如注入:@Autowired  private ApplicationContext ctx; 

 

3、使用

  1. public class User implements Serializable {  
  2.     @Forbidden()  
  3.     private String name;  
  4. }  

 

4、當我們在提交name中含有admin的時候會輸出錯誤消息:

  1. forbidden.word=您輸入的數據中有非法關鍵詞  

 

問題來了,哪個詞是非法的呢?bean validation 和 hibernate validator都沒有提供相應的api提供這個數據,怎麼辦呢?通過跟蹤代碼,發現一種不是特別好的方法:我們可以覆蓋org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl實現(即複製一份代碼放到我們的src中),然後覆蓋buildAnnotationParameterMap方法;

  1. private Map<String, Object> buildAnnotationParameterMap(Annotation annotation) {  
  2.     ……  
  3.     //將Collections.unmodifiableMap( parameters );替換爲如下語句  
  4.     return parameters;  
  5. }  

 即允許這個數據可以修改;然後在ForbiddenValidator中:

  1. for(String word : forbiddenWords) {  
  2.     if(value.contains(word)) {  
  3.         ((ConstraintValidatorContextImpl)context).getConstraintDescriptor().getAttributes().put("word", word);  
  4.         return false;//驗證失敗  
  5.     }  
  6. }  

通過((ConstraintValidatorContextImpl)context).getConstraintDescriptor().getAttributes().put("word", word);添加自己的屬性;放到attributes中的數據可以通過${} 獲取。然後消息就可以變成:

  1. forbidden.word=您輸入的數據中有非法關鍵詞【{word}】  

這種方式不是很友好,但是可以解決我們的問題。

 

典型的如密碼、確認密碼的場景,非常常用;如果沒有這個功能我們需要自己寫代碼來完成;而且經常重複自己。接下來看看bean validation 1.1如何實現的。

 

6、類級別驗證器

6.1、定義驗證註解

  1. package com.sishuok.spring4.validator;  
  2.   
  3. import javax.validation.Constraint;  
  4. import javax.validation.Payload;  
  5. import javax.validation.constraints.NotNull;  
  6. import java.lang.annotation.Documented;  
  7. import java.lang.annotation.Retention;  
  8. import java.lang.annotation.Target;  
  9. import static java.lang.annotation.ElementType.*;  
  10. import static java.lang.annotation.RetentionPolicy.*;  
  11. /** 
  12.  * <p>User: Zhang Kaitao 
  13.  * <p>Date: 13-12-15 
  14.  * <p>Version: 1.0 
  15.  */  
  16.   
  17. @Target({ TYPE, ANNOTATION_TYPE})  
  18. @Retention(RUNTIME)  
  19. //指定驗證器  
  20. @Constraint(validatedBy = CheckPasswordValidator.class)  
  21. @Documented  
  22. public @interface CheckPassword {  
  23.   
  24.     //默認錯誤消息  
  25.     String message() default "";  
  26.   
  27.     //分組  
  28.     Class<?>[] groups() default { };  
  29.   
  30.     //負載  
  31.     Class<? extends Payload>[] payload() default { };  
  32.   
  33.     //指定多個時使用  
  34.     @Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })  
  35.     @Retention(RUNTIME)  
  36.     @Documented  
  37.     @interface List {  
  38.         CheckPassword[] value();  
  39.     }  
  40. }  

6.2、 定義驗證器

  1. package com.sishuok.spring4.validator;  
  2.   
  3. import com.sishuok.spring4.entity.User;  
  4. import org.springframework.util.StringUtils;  
  5.   
  6. import javax.validation.ConstraintValidator;  
  7. import javax.validation.ConstraintValidatorContext;  
  8.   
  9. /** 
  10.  * <p>User: Zhang Kaitao 
  11.  * <p>Date: 13-12-15 
  12.  * <p>Version: 1.0 
  13.  */  
  14. public class CheckPasswordValidator implements ConstraintValidator<CheckPassword, User> {  
  15.   
  16.     @Override  
  17.     public void initialize(CheckPassword constraintAnnotation) {  
  18.     }  
  19.   
  20.     @Override  
  21.     public boolean isValid(User user, ConstraintValidatorContext context) {  
  22.         if(user == null) {  
  23.             return true;  
  24.         }  
  25.   
  26.         //沒有填密碼  
  27.         if(!StringUtils.hasText(user.getPassword())) {  
  28.             context.disableDefaultConstraintViolation();  
  29.             context.buildConstraintViolationWithTemplate("{password.null}")  
  30.                     .addPropertyNode("password")  
  31.                     .addConstraintViolation();  
  32.             return false;  
  33.         }  
  34.   
  35.         if(!StringUtils.hasText(user.getConfirmation())) {  
  36.             context.disableDefaultConstraintViolation();  
  37.             context.buildConstraintViolationWithTemplate("{password.confirmation.null}")  
  38.                     .addPropertyNode("confirmation")  
  39.                     .addConstraintViolation();  
  40.             return false;  
  41.         }  
  42.   
  43.         //兩次密碼不一樣  
  44.         if (!user.getPassword().trim().equals(user.getConfirmation().trim())) {  
  45.             context.disableDefaultConstraintViolation();  
  46.             context.buildConstraintViolationWithTemplate("{password.confirmation.error}")  
  47.                     .addPropertyNode("confirmation")  
  48.                     .addConstraintViolation();  
  49.             return false;  
  50.         }  
  51.         return true;  
  52.     }  
  53. }  

其中我們通過disableDefaultConstraintViolation禁用默認的約束;然後通過buildConstraintViolationWithTemplate(消息模板)/addPropertyNode(所屬屬性)/addConstraintViolation定義我們自己的約束。

 

6.3、使用

  1. @CheckPassword()  
  2. public class User implements Serializable {  
  3. }  

 放到類頭上即可。

 

7、通過腳本驗證

  1. @ScriptAssert(script = "_this.password==_this.confirmation", lang = "javascript", alias = "_this", message = "{password.confirmation.error}")  
  2. public class User implements Serializable {  
  3. }  

通過腳本驗證是非常簡單而且強大的,lang指定腳本語言(請參考javax.script.ScriptEngineManager JSR-223),alias是在腳本驗證中User對象的名字,但是大家會發現一個問題:錯誤消息怎麼顯示呢? 在springmvc 中會添加到全局錯誤消息中,這肯定不是我們想要的,我們改造下吧。

 

7.1、定義驗證註解

  1. package com.sishuok.spring4.validator;  
  2.   
  3. import org.hibernate.validator.internal.constraintvalidators.ScriptAssertValidator;  
  4.   
  5. import java.lang.annotation.Documented;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.Target;  
  8. import javax.validation.Constraint;  
  9. import javax.validation.Payload;  
  10.   
  11. import static java.lang.annotation.ElementType.TYPE;  
  12. import static java.lang.annotation.RetentionPolicy.RUNTIME;  
  13.   
  14. @Target({ TYPE })  
  15. @Retention(RUNTIME)  
  16. @Constraint(validatedBy = {PropertyScriptAssertValidator.class})  
  17. @Documented  
  18. public @interface PropertyScriptAssert {  
  19.   
  20.     String message() default "{org.hibernate.validator.constraints.ScriptAssert.message}";  
  21.   
  22.     Class<?>[] groups() default { };  
  23.   
  24.     Class<? extends Payload>[] payload() default { };  
  25.   
  26.     String lang();  
  27.   
  28.     String script();  
  29.   
  30.     String alias() default "_this";  
  31.   
  32.     String property();  
  33.   
  34.     @Target({ TYPE })  
  35.     @Retention(RUNTIME)  
  36.     @Documented  
  37.     public @interface List {  
  38.         PropertyScriptAssert[] value();  
  39.     }  
  40. }  

和ScriptAssert沒什麼區別,只是多了個property用來指定出錯後給實體的哪個屬性。

 

7.2、驗證器

  1. package com.sishuok.spring4.validator;  
  2.   
  3. import javax.script.ScriptException;  
  4. import javax.validation.ConstraintDeclarationException;  
  5. import javax.validation.ConstraintValidator;  
  6. import javax.validation.ConstraintValidatorContext;  
  7.   
  8. import com.sishuok.spring4.validator.PropertyScriptAssert;  
  9. import org.hibernate.validator.constraints.ScriptAssert;  
  10. import org.hibernate.validator.internal.util.Contracts;  
  11. import org.hibernate.validator.internal.util.logging.Log;  
  12. import org.hibernate.validator.internal.util.logging.LoggerFactory;  
  13. import org.hibernate.validator.internal.util.scriptengine.ScriptEvaluator;  
  14. import org.hibernate.validator.internal.util.scriptengine.ScriptEvaluatorFactory;  
  15.   
  16. import static org.hibernate.validator.internal.util.logging.Messages.MESSAGES;  
  17.   
  18. public class PropertyScriptAssertValidator implements ConstraintValidator<PropertyScriptAssert, Object> {  
  19.   
  20.     private static final Log log = LoggerFactory.make();  
  21.   
  22.     private String script;  
  23.     private String languageName;  
  24.     private String alias;  
  25.     private String property;  
  26.     private String message;  
  27.   
  28.     public void initialize(PropertyScriptAssert constraintAnnotation) {  
  29.         validateParameters( constraintAnnotation );  
  30.   
  31.         this.script = constraintAnnotation.script();  
  32.         this.languageName = constraintAnnotation.lang();  
  33.         this.alias = constraintAnnotation.alias();  
  34.         this.property = constraintAnnotation.property();  
  35.         this.message = constraintAnnotation.message();  
  36.     }  
  37.   
  38.     public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {  
  39.   
  40.         Object evaluationResult;  
  41.         ScriptEvaluator scriptEvaluator;  
  42.   
  43.         try {  
  44.             ScriptEvaluatorFactory evaluatorFactory = ScriptEvaluatorFactory.getInstance();  
  45.             scriptEvaluator = evaluatorFactory.getScriptEvaluatorByLanguageName( languageName );  
  46.         }  
  47.         catch ( ScriptException e ) {  
  48.             throw new ConstraintDeclarationException( e );  
  49.         }  
  50.   
  51.         try {  
  52.             evaluationResult = scriptEvaluator.evaluate( script, value, alias );  
  53.         }  
  54.         catch ( ScriptException e ) {  
  55.             throw log.getErrorDuringScriptExecutionException( script, e );  
  56.         }  
  57.   
  58.         if ( evaluationResult == null ) {  
  59.             throw log.getScriptMustReturnTrueOrFalseException( script );  
  60.         }  
  61.         if ( !( evaluationResult instanceof Boolean ) ) {  
  62.             throw log.getScriptMustReturnTrueOrFalseException(  
  63.                     script,  
  64.                     evaluationResult,  
  65.                     evaluationResult.getClass().getCanonicalName()  
  66.             );  
  67.         }  
  68.   
  69.         if(Boolean.FALSE.equals(evaluationResult)) {  
  70.             constraintValidatorContext.disableDefaultConstraintViolation();  
  71.             constraintValidatorContext  
  72.                     .buildConstraintViolationWithTemplate(message)  
  73.                     .addPropertyNode(property)  
  74.                     .addConstraintViolation();  
  75.         }  
  76.   
  77.         return Boolean.TRUE.equals( evaluationResult );  
  78.     }  
  79.   
  80.     private void validateParameters(PropertyScriptAssert constraintAnnotation) {  
  81.         Contracts.assertNotEmpty( constraintAnnotation.script(), MESSAGES.parameterMustNotBeEmpty( "script" ) );  
  82.         Contracts.assertNotEmpty( constraintAnnotation.lang(), MESSAGES.parameterMustNotBeEmpty( "lang" ) );  
  83.         Contracts.assertNotEmpty( constraintAnnotation.alias(), MESSAGES.parameterMustNotBeEmpty( "alias" ) );  
  84.         Contracts.assertNotEmpty( constraintAnnotation.property(), MESSAGES.parameterMustNotBeEmpty( "property" ) );  
  85.         Contracts.assertNotEmpty( constraintAnnotation.message(), MESSAGES.parameterMustNotBeEmpty( "message" ) );  
  86.     }  
  87. }  

和之前的類級別驗證器類似,就不多解釋了,其他代碼全部拷貝自org.hibernate.validator.internal.constraintvalidators.ScriptAssertValidator。

 

7.3、使用

  1. @PropertyScriptAssert(property = "confirmation", script = "_this.password==_this.confirmation", lang = "javascript", alias = "_this", message = "{password.confirmation.error}")  

和之前的區別就是多了個property,用來指定出錯時給哪個字段。 這個相對之前的類級別驗證器更通用一點。

 

8、cross-parameter,跨參數驗證

直接看示例;

 

8.1、首先註冊MethodValidationPostProcessor,起作用請參考《Spring3.1 對Bean Validation規範的新支持(方法級別驗證) 》 

  1. <bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">  
  2.     <property name="validator" ref="validator"/>  
  3. </bean>  

 

8.2、Service 

  1. @Validated  
  2. @Service  
  3. public class UserService {  
  4.   
  5.     @CrossParameter  
  6.     public void changePassword(String password, String confirmation) {  
  7.   
  8.     }  
  9. }  

通過@Validated註解UserService表示該類中有需要進行方法參數/返回值驗證;   @CrossParameter註解方法表示要進行跨參數驗證;即驗證password和confirmation是否相等。

 

8.3、驗證註解 

  1. package com.sishuok.spring4.validator;  
  2.   
  3. //省略import  
  4.   
  5. @Constraint(validatedBy = CrossParameterValidator.class)  
  6. @Target({ METHOD, CONSTRUCTOR, ANNOTATION_TYPE })  
  7. @Retention(RUNTIME)  
  8. @Documented  
  9. public @interface CrossParameter {  
  10.   
  11.     String message() default "{password.confirmation.error}";  
  12.     Class<?>[] groups() default { };  
  13.     Class<? extends Payload>[] payload() default { };  
  14.   
  15. }  

 

8.4、驗證器 

  1. package com.sishuok.spring4.validator;  
  2.   
  3. //省略import  
  4.   
  5. @SupportedValidationTarget(ValidationTarget.PARAMETERS)  
  6. public class CrossParameterValidator implements ConstraintValidator<CrossParameter, Object[]> {  
  7.   
  8.     @Override  
  9.     public void initialize(CrossParameter constraintAnnotation) {  
  10.     }  
  11.   
  12.     @Override  
  13.     public boolean isValid(Object[] value, ConstraintValidatorContext context) {  
  14.         if(value == null || value.length != 2) {  
  15.             throw new IllegalArgumentException("must have two args");  
  16.         }  
  17.         if(value[0] == null || value[1] == null) {  
  18.             return true;  
  19.         }  
  20.         if(value[0].equals(value[1])) {  
  21.             return true;  
  22.         }  
  23.         return false;  
  24.     }  
  25. }  

其中@SupportedValidationTarget(ValidationTarget.PARAMETERS)表示驗證參數; value將是參數列表。 

 

8.5、使用

  1. @RequestMapping("/changePassword")  
  2. public String changePassword(  
  3.         @RequestParam("password") String password,  
  4.         @RequestParam("confirmation") String confirmation, Model model) {  
  5.     try {  
  6.         userService.changePassword(password, confirmation);  
  7.     } catch (ConstraintViolationException e) {  
  8.         for(ConstraintViolation violation : e.getConstraintViolations()) {  
  9.             System.out.println(violation.getMessage());  
  10.         }  
  11.     }  
  12.     return "success";  
  13. }  

調用userService.changePassword方法,如果驗證失敗將拋出ConstraintViolationException異常,然後得到ConstraintViolation,調用getMessage即可得到錯誤消息;然後到前臺顯示即可。

 

從以上來看,不如之前的使用方便,需要自己對錯誤消息進行處理。 下一節我們也寫個腳本方式的跨參數驗證器。

 

9、混合類級別驗證器和跨參數驗證器

9.1、驗證註解

  1. package com.sishuok.spring4.validator;  
  2.   
  3. //省略import  
  4.   
  5. @Constraint(validatedBy = {  
  6.         CrossParameterScriptAssertClassValidator.class,  
  7.         CrossParameterScriptAssertParameterValidator.class  
  8. })  
  9. @Target({ TYPE, FIELD, PARAMETER, METHOD, CONSTRUCTOR, ANNOTATION_TYPE })  
  10. @Retention(RUNTIME)  
  11. @Documented  
  12. public @interface CrossParameterScriptAssert {  
  13.     String message() default "error";  
  14.     Class<?>[] groups() default { };  
  15.     Class<? extends Payload>[] payload() default { };  
  16.     String script();  
  17.     String lang();  
  18.     String alias() default "_this";  
  19.     String property() default "";  
  20.     ConstraintTarget validationAppliesTo() default ConstraintTarget.IMPLICIT;  
  21. }   

 

此處我們通過@Constraint指定了兩個驗證器,一個類級別的,一個跨參數的。validationAppliesTo指定爲ConstraintTarget.IMPLICIT,表示隱式自動判斷。

 

9.2、驗證器

請下載源碼查看

 

9.3、使用

9.3.1、類級別使用

  1. @CrossParameterScriptAssert(property = "confirmation", script = "_this.password==_this.confirmation", lang = "javascript", alias = "_this", message = "{password.confirmation.error}")  

指定property即可,其他和之前的一樣。

9.3.2、跨參數驗證

  1. @CrossParameterScriptAssert(script = "args[0] == args[1]", lang = "javascript", alias = "args", message = "{password.confirmation.error}")  
  2. public void changePassword(String password, String confirmation) {  
  3.   
  4. }  

通過args[0]==args[1] 來判斷是否相等。

 

這樣,我們的驗證註解就自動適應兩種驗證規則了。  

 

 

 

到此,我們已經完成大部分Bean Validation的功能實驗了。對於如XML配置、編程式驗證API的使用等對於我們使用SpringMVC這種web環境用處不大,所以就不多介紹了,有興趣可以自己下載官方文檔學習。


發佈了104 篇原創文章 · 獲贊 13 · 訪問量 86萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章