Hibernate Validation使用示例及講解

在項目開發過程當中,後臺在不少場景都須要進行校驗操做,好比:前臺表單提交到後臺,系統接口調用,數據傳輸等等。並且不少項目都採用MVC分層式設計,每層還有須要進行相應地校驗,這樣在項目較大,多人協做開發的時候,會形成大量重複校驗代碼,且出錯率高。javascript

針對這個問題,JCP出臺一個JSR 303-Bean Validation規範,而Hibernate Validator 做爲Bean Validation的參考實現,提供了JSR 303規範中全部內置constraint的實現,除此以外還有一些附加的constraint。html

Hibernate Validation的使用很是簡單,只用在相應的實體類中加上註解,再調用對應的校驗API方法便可。java

Hibernate Validation目前最新的穩定版本是:5.1.3。下載地址git

官網地址 
官方英文使用手冊 
官方中文使用手冊地址(中文版目前最新的是4.3版本)github

具體使用方法請查看上面的官方使用手冊地址,每一個註解對應的含義在官方手冊2.4章節有詳細介紹,內容太多我就不貼過來了。下面直接上最經常使用狀況(實體類校驗)的示例代碼。web

1、依賴包api

J2SE環境下除了須要引入Hibernate Validation包外,還須要額外引入兩個實現表達式語言的包。J2EE環境若是容器提供不須要再引入。下面是J2SE環境下的依賴包:app

Xml代碼 框架

 收藏代碼

  1. <dependency>  
  2.             <groupId>org.hibernate</groupId>  
  3.             <artifactId>hibernate-validator</artifactId>  
  4.             <version>5.1.3.Final</version>  
  5.         </dependency>  
  6.         <dependency>  
  7.             <groupId>javax.el</groupId>  
  8.             <artifactId>javax.el-api</artifactId>  
  9.             <version>2.2.4</version>  
  10.         </dependency>  
  11.         <dependency>  
  12.             <groupId>org.glassfish.web</groupId>  
  13.             <artifactId>javax.el</artifactId>  
  14.             <version>2.2.4</version>  
  15.         </dependency>  

 

2、校驗工具類ide

工具類提供了校驗實體類、實體字段的方法,返回一個自定義的校驗對象。

Java代碼 

 收藏代碼

  1. /** 
  2.  * 校驗工具類 
  3.  * @author wdmcygah 
  4.  * 
  5.  */  
  6. public class ValidationUtils {  
  7.   
  8.     private static Validator validator =  Validation.buildDefaultValidatorFactory().getValidator();  
  9.       
  10.     public static <T> ValidationResult validateEntity(T obj){  
  11.         ValidationResult result = new ValidationResult();  
  12.          Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);  
  13.          if( CollectionUtils.isNotEmpty(set) ){  
  14.              result.setHasErrors(true);  
  15.              Map<String,String> errorMsg = new HashMap<String,String>();  
  16.              for(ConstraintViolation<T> cv : set){  
  17.                  errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());  
  18.              }  
  19.              result.setErrorMsg(errorMsg);  
  20.          }  
  21.          return result;  
  22.     }  
  23.       
  24.     public static <T> ValidationResult validateProperty(T obj,String propertyName){  
  25.         ValidationResult result = new ValidationResult();  
  26.          Set<ConstraintViolation<T>> set = validator.validateProperty(obj,propertyName,Default.class);  
  27.          if( CollectionUtils.isNotEmpty(set) ){  
  28.              result.setHasErrors(true);  
  29.              Map<String,String> errorMsg = new HashMap<String,String>();  
  30.              for(ConstraintViolation<T> cv : set){  
  31.                  errorMsg.put(propertyName, cv.getMessage());  
  32.              }  
  33.              result.setErrorMsg(errorMsg);  
  34.          }  
  35.          return result;  
  36.     }  
  37. }  

 

3、校驗返回對象

Java代碼 

 收藏代碼

  1. <span style="line-height: 22.3999996185303px;">/** 
  2.  * 校驗結果 
  3.  * @author wdmcygah 
  4.  * 
  5.  */  
  6. public class ValidationResult {  
  7.   
  8.     //校驗結果是否有錯  
  9.     private boolean hasErrors;  
  10.       
  11.     //校驗錯誤信息  
  12.     private Map<String,String> errorMsg;  
  13.   
  14.     public boolean isHasErrors() {  
  15.         return hasErrors;  
  16.     }  
  17.   
  18.     public void setHasErrors(boolean hasErrors) {  
  19.         this.hasErrors = hasErrors;  
  20.     }  
  21.   
  22.     public Map<String, String> getErrorMsg() {  
  23.         return errorMsg;  
  24.     }  
  25.   
  26.     public void setErrorMsg(Map<String, String> errorMsg) {  
  27.         this.errorMsg = errorMsg;  
  28.     }  
  29.   
  30.     @Override  
  31.     public String toString() {  
  32.         return "ValidationResult [hasErrors=" + hasErrors + ", errorMsg="  
  33.                 + errorMsg + "]";  
  34.     }  
  35.   
  36. }</span>  

4、被校驗實體

Java代碼 

 收藏代碼

  1. public class SimpleEntity {  
  2.   
  3.     @NotBlank(message="名字不能爲空或者空串")  
  4.     @Length(min=2,max=10,message="名字必須由2~10個字組成")  
  5.     private String name;  
  6.       
  7.     @Past(message="時間不能晚於當前時間")  
  8.     private Date date;  
  9.       
  10.     @Email(message="郵箱格式不正確")  
  11.     private String email;  
  12.       
  13.     @Pattern(regexp="(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,10}",message="密碼必須是5~10位數字和字母的組合")  
  14.     private String password;  
  15.       
  16.     @AssertTrue(message="字段必須爲真")  
  17.     private boolean valid;  
  18.     
  19.        //get set方法省略,本身添加  
  20. }  

 

有些狀況下,Hibernate Validation自帶的註解不可以知足需求,咱們想定製一個註解進行使用,此時能夠參考下面的示例(自定義密碼註解及校驗規則)。

1、密碼註解

Java代碼 

 收藏代碼

  1. package research.hibernate.validation.extend;  
  2.   
  3. import static java.lang.annotation.ElementType.ANNOTATION_TYPE;  
  4. import static java.lang.annotation.ElementType.FIELD;  
  5. import static java.lang.annotation.ElementType.METHOD;  
  6. import static java.lang.annotation.RetentionPolicy.RUNTIME;  
  7.   
  8. import java.lang.annotation.Documented;  
  9. import java.lang.annotation.Retention;  
  10. import java.lang.annotation.Target;  
  11.   
  12. import javax.validation.Constraint;  
  13. import javax.validation.Payload;  
  14.   
  15. @Target( { METHOD, FIELD, ANNOTATION_TYPE })  
  16. @Retention(RUNTIME)  
  17. @Constraint(validatedBy = PasswordValidator.class)  
  18. @Documented  
  19. public @interface Password {  
  20.   
  21.     String message() default "{密碼必須是5~10位數字和字母組合}";  
  22.   
  23.     Class<?>[] groups() default {};  
  24.   
  25.     Class<? extends Payload>[] payload() default {};  
  26. }  

 

2、密碼校驗類

Java代碼 

 收藏代碼

  1. /** 
  2.  * 自定義密碼校驗類 
  3.  * @author wdmcygah 
  4.  * 
  5.  */  
  6. public class PasswordValidator implements ConstraintValidator<Password, String> {  
  7.   
  8.     //5~10位的數字與字母組合  
  9.     private static Pattern pattern = Pattern.compile("(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,10}");  
  10.       
  11.     public void initialize(Password constraintAnnotation) {  
  12.         //do nothing  
  13.     }  
  14.   
  15.     public boolean isValid(String value, ConstraintValidatorContext context) {  
  16.         if( value==null ){  
  17.             return false;  
  18.         }  
  19.         Matcher m = pattern.matcher(value);  
  20.         return m.matches();  
  21.     }     
  22. }  

 

3、被校驗實體

Java代碼 

 收藏代碼

  1. public class ExtendEntity {  
  2.   
  3.     @Password  
  4.     private String password;  
  5.       
  6.     public String getPassword() {  
  7.         return password;  
  8.     }  
  9.   
  10.     public void setPassword(String password) {  
  11.         this.password = password;  
  12.     }  
  13.   
  14. }  

 

對應的測試類以下:

Java代碼 

 收藏代碼

  1. public class ValidationUtilsTest extends TestCase{  
  2.   
  3.   public void validateSimpleEntity() {  
  4.       SimpleEntity se = new SimpleEntity();  
  5.       se.setDate(new Date());  
  6.       se.setEmail("123");  
  7.       se.setName("123");  
  8.       se.setPassword("123");  
  9.       se.setValid(false);  
  10.       ValidationResult result = ValidationUtils.validateEntity(se);  
  11.       System.out.println("--------------------------");  
  12.       System.out.println(result);  
  13.       Assert.assertTrue(result.isHasErrors());  
  14.   }  
  15.     
  16.   public void validateSimpleProperty() {  
  17.       SimpleEntity se = new SimpleEntity();  
  18.       ValidationResult result = ValidationUtils.validateProperty(se,"name");  
  19.       System.out.println("--------------------------");  
  20.       System.out.println(result);  
  21.       Assert.assertTrue(result.isHasErrors());  
  22.   }  
  23.     
  24.   public void validateExtendEntity() {  
  25.       ExtendEntity ee = new ExtendEntity();  
  26.       ee.setPassword("212");  
  27.       ValidationResult result = ValidationUtils.validateEntity(ee);  
  28.       System.out.println("--------------------------");  
  29.       System.out.println(result);  
  30.       Assert.assertTrue(result.isHasErrors());  
  31.   }  
  32. }  

 

代碼在JDK1.8下測試經過。完整代碼可查看個人Github倉庫:https://github.com/wdmcygah/research-J2SE

 

備註:
(1)上述示例只是展現了Hibernate Validation比較經常使用的示例,框架其實還支持方法返回值、方法參數校驗,另外也能夠經過XML進行配置,校驗還能夠分組、合併等等。這些內容請查閱官方使用手冊。
(2)另外還有一個也還不錯的校驗框架:OVAL。OVAL源碼地址

相關文章
相關標籤/搜索