• hibernate_validator_10


    约束条件组合--把多个约束组合成一个约束

    上一节中我们自定义的@CheckCase是用来检查是否String为大写的注释,默认情况下当我们的String为null的时候也被认为正确的

    CaseMode枚举

    package test02;
    
    public enum CaseMode {
        UPPER,
        LOWER;
    }
    View Code

    User类

    package test02;
    
    public class User {
        @CheckCase(value=CaseMode.UPPER)
        private String name;
        
    //    @CheckCase(CaseMode.UPPER)
    //    private String email="email";
    }

    @CheckCase

    package test02;
    
    import static java.lang.annotation.ElementType.*;
    import static java.lang.annotation.RetentionPolicy.*;
    import java.lang.annotation.Documented;
    import java.lang.annotation.Retention;
    import java.lang.annotation.Target;
    import javax.validation.Constraint;
    import javax.validation.Payload;
    @Target({METHOD, FIELD, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    @Constraint(validatedBy = CheckCaseValidator.class)
    @Documented
    public @interface CheckCase {
        String message() default "{test02.CheckCase.message}";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
        CaseMode value();
    
    }
    View Code

    验证器

    package test02;
    
    import javax.validation.ConstraintValidator;
    import javax.validation.ConstraintValidatorContext;
    
    public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {
        private CaseMode caseMode;
    
        public void initialize(CheckCase constraintAnnotation) {
            this.caseMode = constraintAnnotation.value();
        }
    
        public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
            if (object == null)
                return true;
            boolean isValid;
            if (caseMode == CaseMode.UPPER) {
                isValid = object.equals(object.toUpperCase());
            } else {
                isValid = object.equals(object.toLowerCase());
            }
    //        if(!isValid) {
    //            constraintContext.disableDefaultConstraintViolation();
    //            constraintContext.buildConstraintViolationWithTemplate( "{com.mycompany.constraints.CheckCase.message}" ).addConstraintViolation();
    //            }
            return isValid;
        }
    }
    View Code

    运行结果:

    @Test
        public void test01(){
            User u=new User();
            Set<ConstraintViolation<User>> validate = validator.validate(u);
            System.out.println(validate.size());
            //0
            System.out.println(validate);
            //[]
        }

    所以这一节我们将该注释和@notNull的注释组合起来

    一,创建一个约束条件组合 @UpperNotNull

    package test03;
    import static java.lang.annotation.ElementType.*;
    import static java.lang.annotation.RetentionPolicy.*;
    import java.lang.annotation.Documented;
    import java.lang.annotation.Retention;
    import java.lang.annotation.Target;
    
    import javax.validation.Constraint;
    import javax.validation.Payload;
    import javax.validation.constraints.NotNull;
    
    import test02.CheckCase;
    import test02.CaseMode;
    
    @NotNull
    @CheckCase(CaseMode.UPPER)
    @Target( { METHOD, FIELD, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    @Constraint(validatedBy = {})
    @Documented
    public @interface UpperNotNull {
        String message() default "{com.mycompany.constraints.validlicenseplate}";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    
    }
    package test02;
    
    import static java.lang.annotation.ElementType.*;
    import static java.lang.annotation.RetentionPolicy.*;
    import java.lang.annotation.Documented;
    import java.lang.annotation.Retention;
    import java.lang.annotation.Target;
    import javax.validation.Constraint;
    import javax.validation.Payload;
    @Target({METHOD, FIELD, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    @Constraint(validatedBy = CheckCaseValidator.class)
    @Documented
    public @interface CheckCase {
        String message() default "{test02.CheckCase.message}";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
        CaseMode value();
    
    }

    属性文件中的内容

    test02.CheckCase.message = must be false {value}
    com.mycompany.constraints.validlicenseplate=must not be null and must be Upper writen 

    二,创建Po测试类

    package test03;
    
    public class User {
        @UpperNotNull
        private String name;
        
    //    @CheckCase(CaseMode.UPPER)
    //    private String email="email";
    }

     三,测试

    package test03;
    
    import java.util.Set;
    
    import javax.validation.ConstraintViolation;
    import javax.validation.Validation;
    import javax.validation.Validator;
    import javax.validation.ValidatorFactory;
    import org.junit.BeforeClass;
    import org.junit.Test;
    public class MyTest {
    
        private static Validator validator;
    
        /**
         * 获取一个验证器
         */
        @BeforeClass
        public static void setUp() {
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            validator = factory.getValidator();
        }
        @Test
        public void test01(){
            User u=new User();
            Set<ConstraintViolation<User>> validate = validator.validate(u);
            System.out.println(validate.size());
            //1
            System.out.println(validate);
            //[ConstraintViolationImpl{interpolatedMessage='不能为null', propertyPath=name, rootBeanClass=class test03.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}]
        }
    
    }

    当我们把Po类中的name改成:

    package test03;
    
    public class User {
        @UpperNotNull
        private String name="wangyang";
        
    //    @CheckCase(CaseMode.UPPER)
    //    private String email="email";
    }

    再测试:

    @Test
        public void test01(){
            User u=new User();
            Set<ConstraintViolation<User>> validate = validator.validate(u);
            System.out.println(validate.size());
            //1
            System.out.println(validate);
            //[ConstraintViolationImpl{interpolatedMessage='must be false UPPER', propertyPath=name, rootBeanClass=class test03.User, messageTemplate='{test02.CheckCase.message}'}]
        }
  • 相关阅读:
    构建之法阅读笔记01
    软件工程个人作业01
    第一个PSP0级
    java实现课表的增加
    软件工程概论01
    异常处理
    流与文件课件课后作业1计算容量
    第九周课堂测试
    第八周动手动脑
    JAVA项目中常用的异常知识点总结
  • 原文地址:https://www.cnblogs.com/wangyang108/p/5670871.html
Copyright © 2020-2023  润新知