java后端对象属性验证,Hibernate-Validation

    Hibernate-Validation

 

一.依赖架包:

           validation-api-1.0.0.GA.jar

           hibernate-validator-4.3.1.final-1.0.0.jar

          

二.校验工具类

public class ValidationUtils {

          privatestatic Validator validator =  Validation.buildDefaultValidatorFactory().getValidator();

          publicstatic ValidationResultvalidateEntity(T obj){

               ValidationResultresult = new ValidationResult();

                    Set> set =validator.validate(obj,Default.class);

               if(CollectionUtils.isNotEmpty(set)){

                                              result.setHasErrors(true);

                                MaperrorMsg = newHashMap();

                                              for(ConstraintViolationcv : set){

                                                   errorMsg.put(cv.getPropertyPath().toString(),cv.getMessage());

                                               }

                                              result.setErrorMsg(errorMsg);

                                }

                               returnresult;

               }

       publicstatic ValidationResultvalidateProperty(T obj,StringpropertyName){

              ValidationResultresult = new ValidationResult();

                   Set> set =validator.validateProperty(obj,propertyName,Default.class);

                               if(CollectionUtils.isNotEmpty(set)){

                                              result.setHasErrors(true);

                                MaperrorMsg = newHashMap();

                                              for(ConstraintViolationcv : set){

                                              errorMsg.put(propertyName,cv.getMessage());

                                               }

                                              result.setErrorMsg(errorMsg);

                                }

                               returnresult;

               }

}

三、校验返回对象

public class ValidationResult{

       //校验结果是否有错

       private boolean hasErrors;

       //校验错误信息

       private Map errorMsg;

       public boolean getHasErrors(){

              return hasErrors;

       }

       public void setHasErrors(boolean hasErrors){

              this.hasErrors = hasErrors;

       }

       public Map getErrorMsg(){

              return errorMsg;

       }

       public void setErrorMsg(Map errorMsg){

              this.errorMsg = errorMsg;

       }

       @Override

       public String toString(){

              return "ValidationResult[hasErrors=" + hasErrors + ", errorMsg=" + errorMsg + "]";

       }

}

四.实体类

public class SimpleEntity {
               @NotBlank(message="名字不能为空或者空串")
               @Length(min=2, max=10, message="名字必须由2~10个字组成")
               private String name;
               @Past(message="时间不能晚于当前时间")
               private Date date;
               @Email(message="邮箱格式不正确")
               private String email;
               @Pattern(regexp="(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,10}",message="密码必须是5~10位数字和字母的组合")
               private String password;
               @AssertTrue(message="字段必须为真")
               private boolean valid;
               //get set方法省略,自己添加
}

五.校验

public void validateSimpleEntity() {
               SimpleEntity se = new SimpleEntity();
               se.setDate(new Date());
               se.setEmail("123");
               se.setName("123");
               se.setPassword("123");
               se.setValid(false);
ValidationResult result = ValidationUtils.validateEntity(se);
               System.out.println("--------------------------");
               System.out.println(result);
               Assert.assertTrue(result.isHasErrors());
  }
返回结果:
ValidationResult [hasErrors=true, errorMsg={name=名字不能为空或者空串}]
ValidationResult [hasErrors=false, errorMsg=null]

六.自定义注解

       若hibernate提供注解不够使用可自定义
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
@Documented
public @interface Password {
    String message() default"{密码必须是5~10位数字和字母组合}";
    Class[] groups() default {};
    Class[] payload() default {};
}

七、密码校验类

/**
 * 自定义密码校验类
 */
public class PasswordValidator implements ConstraintValidator{
               //5~10位的数字与字母组合
               privatestatic Pattern pattern = Pattern.compile("(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,10}");
               public void initialize(Password constraintAnnotation){
                               //do nothing
               }
               public boolean isValid(String value, ConstraintValidatorContext context){
                               if( value==null ){
                                              returnfalse;
                               }
                               Matcher m = pattern.matcher(value);
                               return m.matches();
               }              
}

你可能感兴趣的:(java后端对象属性验证,Hibernate-Validation)