spring boot项目使用validate校验

第一步:引入依赖

<!--validate依赖  校验-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

提供了很多注解来辅助校验在这里插入图片描述

在实体类字段上使用(请求过程中会自动校验)

@Data
public class LoginVo {

    @NotNull
    private String mobile;

    @NotNull//不为null
    @Length(min = 32)//长度最小为32
    private String password;
}

注解内容:
在这里插入图片描述

自定义注解@IsMobile

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

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

}

通过validate中的注解直接复制创建注解:

/**
 * @author 创建自定义注解
 * @date 2022/1/11 - 15:18
 */
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class})//IsMobileValidator注解校验的类
public @interface IsMobile {
    boolean required() default true;//判断是否必填

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

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

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

自定义校验规则

/**
 * @description: 自定义注解的校验规则
 * @author 孙
 * @date 2022/1/11 15:20
 * @version 1.0
 */
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);
            }
        }
    }
}

/**
 * @description: 校验工具类
 * @author 孙
 * @date 2022/1/11 14:44
 * @version 1.0
 */
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();
    }
}

测试

    @RequestMapping("/doLogin")
    @ResponseBody
    public RespBean doLogin(@Valid LoginVo loginVo){//@Valid启动注解校验
        log.info(loginVo.toString());//使用@Slf4j注解打印日志
        return userService.login(loginVo);
    }
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值