学无先后,达者为师

网站首页 编程语言 正文

SpringBoot的数据校验(@Validated注解)、关于validation无法导入的问题解决、自定义校验注解

作者:@黑夜中的一盏明灯 更新时间: 2022-07-30 编程语言

一:SpringBoot的数据校验(@Validated注解)、关于validation无法导入的问题解决

在springboot中,@Validated可对后台接收model进行数据校验,不符合则抛出异常。
导入依赖:

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

如果在你导入validation包的时候,出现爆红,检查springboot的版本,本人亲测validation在springboot的2.3.4.RELEASE版本可以导入,不会出现问题其他问题
在这里插入图片描述

使用样例:
1.在实体类中定义注解

@Data
@EqualsAndHashCode(callSuper = false)
@TableName("sys_role")
@ApiModel(value="Role对象", description="")
public class Role implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @NotNull(message = "角色名称不能为空")
    private String name;

    @NotNull(message = "角色编码不能为空")
    private String code;

    @ApiModelProperty(value = "备注")
    private String remark;

    private LocalDateTime created;

    private LocalDateTime updated;

    private Integer statu;

    @TableField(exist = false)
    private List<Long> menuIds = new ArrayList<>();


}

2.在controller层的方法形参前进行声明

 @PostMapping("/save")
    public Result save(@Validated @RequestBody Role role){
        role.setCreated(LocalDateTime.now());
        role.setStatu(Const.STATIC_OFF);

        roleService.save(role);
        return Result.succ(role);
    }

常用注解:

@AssertFalse 校验false
@AssertTrue 校验true
@DecimalMax(value=,inclusive=) 小于等于value,inclusive=true,是小于等于
@DecimalMin(value=,inclusive=) 与上类似
@Max(value=) 小于等于value
@Min(value=) 大于等于value
@NotNull  检查Null
@Past  检查日期
@Pattern(regex=,flag=)  正则
@Size(min=, max=)  字符串,集合,map限制大小
@Validate 对po实体类进行校验(若modelA中存在modelB,可使用@Validate声明modelB进行校验,具体校验规则在modelB进行声明)

二:自定义校验注解

在这里插入图片描述
自定义 @IsMobile注解演示:由于下面的代码是本人在项目中粘贴出的,会有一些包没有的现象,请大家见谅。
第一步:新建一个IsMobile类

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@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 { };
}

第二步:@Constraint(validatedBy = { IsMobileValidator.class})定义校验类

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);
            }
        }

    }
}

上面使用的ValidatorUtil类

/**
 * 手机号码校验
 */
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();
    }


}

原文链接:https://blog.csdn.net/qq_51269815/article/details/124919509

栏目分类
最近更新