栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring boot项目使用validate校验

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring boot项目使用validate校验

第一步:引入依赖

        
            org.springframework.boot
            spring-boot-starter-validation
        

提供了很多注解来辅助校验

在实体类字段上使用(请求过程中会自动校验)
@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中的注解直接复制创建注解:
@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[] payload() default { };
}

自定义校验规则
public class IsMobilevalidator implements ConstraintValidator {
    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);
            }
        }
    }
}

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);
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/703340.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号