zoukankan      html  css  js  c++  java
  • ConstraintValidator自定义注解

      自定义接口

    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = PasswordValidator.class)
    public @interface Password {
    
        String type() default "default";
    
        /**
         * 默认错误消息
         *
         * @return
         */
        String message() default "密码过于简单";
    
        /**
         * 分组
         *
         * @return
         */
        Class<?>[] groups() default {};
    
        /**
         * 负载
         *
         * @return
         */
        Class<? extends Payload>[] payload() default {};
    }

      实现自定义接口

      type用于标识符 通过constraintAnnotation.type()对type初始化

      下面判断type就可以对注解进行扩展

    public class PasswordValidator implements ConstraintValidator<Password, Object> {
    
        private String type;
        @Override
        public void initialize(Password constraintAnnotation) {
            type = constraintAnnotation.type();
        }
    
        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            switch (type){
                case "1":
                    if(value.equals("123")){
                        return true;
                    }
                    return false;
                case"2":
                    System.out.println(456);
                    return true;
           default: System.out.println("谢谢"); true; } return true; } }

      定义实体类

      定义好type值

    @Data
    public class Text {
        @NotBlank
        @Password(type = "1",message = "不存在")
        private String text;
    }

      controller

    @GetMapping("/test")
    public String test(@Validated Text text){
      System.out.println(text);
      return text.getText();
    }

      如果spring自带的@Validated 不生效可能版本冲突注解不生效  导入如下依赖 就可以解决不生效问题

    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
    </dependency>
  • 相关阅读:
    POJ 3279 Fliptile
    FZU 2143 Board Game
    【HDU 5015】233 Matrix
    【BZOJ 2463】 谁能赢呢?
    【POJ 2311】 Cutting Game
    【HDU 1846】 Brave Game
    【HDU 1847】 Good Luck in CET-4 Everybody!
    【Codeforces 258D】 Count Good Substrings
    【Codeforces 258B】 Sort the Array
    【Codeforces 258A】 Game With Sticks
  • 原文地址:https://www.cnblogs.com/liljoker/p/13747591.html
Copyright © 2011-2022 走看看