目录

自定义注解校验

李羽秋
李羽秋 2022年02月07日  ·  阅读 914

自定义注解校验

1.导入依赖

 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

2.编写校验工具类

public class ValidatorUtil {
    private static final Pattern mobile_pattern = Pattern.compile("[1][3-9][0-9]{9}$");
    public static boolean isMobile(String mobile){
        if(StringUtils.isEmpty(mobile))
            return false;
        Matcher matcher = mobile_pattern.matcher(mobile);
        return matcher.matches();
    }
}

3.在controller层参数上加@valid注解

/***
     * 登录功能
     * @param loginVo
     * @return
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public RespBean doLogin( @Valid LoginVo loginVo){

        return  userService.doLogin(loginVo);
    }

4. 给LoginVo添加自定义校验规则

@Data
public class LoginVo {
    @NotNull
    @IsMobile
    private String mobile;

    @NotNull
    @Length(min =32)
    private String password;

}

@IsMobile是我们自定义的规则

5. 新建IsMobile注解类

 (上面几个注解从Not NuLL 注解复制过来)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {
    boolean required() default true;

    String message() default "手机号码格式错误";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

6. 编写 IsMobileValidator 类

public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {
    private boolean required =false;
    @Override
    public void initialize(IsMobile constraintAnnotation) {
       required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(required){
            return ValidatorUtil.isMobile(value);
        }else {
            if (StringUtils.isEmpty(value)){
                return  true;
            }
            else {
                return ValidatorUtil.isMobile(value);
            }
        }
        }
}
分类:
标签: