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

    需求原型是

    许多接口都需要 userId 作为参数,参与接口的调用,但是很多情况下,传入不存在的userId 到数据库,会产生脏数据,因此需要在接口接收userId 的时候校验用户表是否存在此 userId

    第一步:自定义注解 CheckUser

    @Target({ElementType.PARAMETER,ElementType.FIELD,ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = CheckUserImpl.class)
    public @interface CheckUser {
    
        /**
         * 是否允许为空
         *
         * @return
         */
        boolean allowNull() default false;
    
        /**
         * 是否需要校验(如果单纯只是想作为swagger提示展示的时候就设置为false)
         *
         * @return
         */
        boolean doValid() default true;
    
        /**
         * 提示信息
         *
         * @return
         */
        String message() default "用户id不存在";
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    
        /**
         * 是否隐藏参数
         *
         * @return
         */
        boolean hideDescription() default false;
    }

    第二步:编写注解的实现类 CheckUserImpl

    @Slf4j
    @Aspect
    @Component
    public class CheckUserImpl implements ConstraintValidator<CheckUser,Long> {
    
        private CheckUser constraintAnnotation;
        @Autowired
        private ValidateDao validDao;
    
    
        @Override
        public boolean isValid(Long value, ConstraintValidatorContext context) {
            if (value == null || value == 0) {
                return constraintAnnotation.allowNull();
            }
            boolean doValid = this.constraintAnnotation.doValid();
            if (!doValid) {
                return true;
            }
            Integer result = validDao.validUserId(value);
            if(result >0){
                return true;
            }
            return false;
        }
    
        @Override
        public void initialize(CheckUser constraintAnnotation) {
            this.constraintAnnotation = constraintAnnotation;
        }
    }

    在实现类中,ValidateDao 为 mybatis 提供的接口

    第三步:在参数处指定需要校验的 UserId

  • 相关阅读:
    jQuery工具函数
    jqXHR对象
    跨域获取
    Ajax :六个全局事件
    表单序列化
    Ajax : $. get()和$.post() $.getScript $.getJSON
    Ajax : load()
    列队动画
    关于MindManager显示不同级别的控制
    Mybatis 查询传多个参数(3中方法)
  • 原文地址:https://www.cnblogs.com/bytecodebuffer/p/14063235.html
Copyright © 2011-2022 走看看