SpringBoot uses JSR303 to verify the entity class submitted by the form

  When we submit the form, we will verify the legality and correctness of the submitted data. Using JSR303 verification can facilitate the data verification function; JSR303 provides our commonly used verification rules and encapsulates them into annotations. We directly use annotations for verification when we use it
Insert picture description here

@AssertTrue 	验证 Boolean 对象是否为 true 
@AssertFalse 	验证 Boolean 对象是否为 false
@DecimalMax 	被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度 
@DecimalMin 	被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度 
@Digits 		验证 Number 是否在某个范围内 
@Email 			验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@Future 		验证 Date 和 Calendar 对象是否在当前时间之后 ,验证成立的话被注释的元素一定是一个将来的日期
@FutureOrPresent带注释的元素必须是当前或将来的瞬间、日期或时间
@Min 			验证 Number 是否大等于指定的值 
@Max			验证 Number 是否小等于指定的值  
@Negative		验证 number 是负数
@NegativeOrZero	验证 number 是负数 或者 0
@NotBlank		验证String 不为null并且至少包含一个非空字符
@NotEmpty		验证String 不为null或者不为空
@NotNull		验证String 不为null
@Null			验证String 为null
@Past			验证为过去的日期
@PastOrPresent	验证为过去或现在的日期
@Pattern		自定义正则表达式验证
@Positive		验证 number 是正数
@PositiveOrZero	验证 number 是正数或0
@Size			验证在某个范围之间
jar package dependency
<!-- 普通Maven -->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>7.0.0.CR1</version>
</dependency>
<!-- SpringBoot -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Simple check

  Add annotations to be validated on the attributes of the received entity class, and use @Valid to enable validation on the interface of the received entity class

/**
 * 接口
 */
@PutMapping("/save")
public R save(@Valid @RequestBody TestEntity test) {
    
    
   return R.ok();
}

/**
 * 实体类
 */
public class TestEntity implements Serializable {
    
    
	@NotBlank(message = "姓名不能为空")
    private String name;

    @NotBlank(message = "logo地址不能为空")
    private String logo;
}
Packet check

  For example, we use the same entity class when adding and updating data, but in different operations, different parameters need to be verified. You can use grouping for verification;
note that if the entity class attribute does not specify the grouping, and the grouping is enabled on the interface Validation, then the attributes that are not grouped will not be checked during validation, even if these attributes have annotations

/**
 * 首先编写分组的空接口
 * 例如我们需要区分更新和新增两个操作
 */
 //新增时的分组接口
public interface AddGroup {
    
    }
 //更新时的分组接口
public interface UpdateGroup {
    
    }

/**
 * 实体类表标注分组信息
 */
 public class TestEntity implements Serializable {
    
    
	@NotBlank(message = "姓名不能为空", groups = {
    
    AddGroup.class})//只在新增时进行验证
    private String name;

    @NotBlank(message = "logo地址不能为空", groups = {
    
    UpdateGroup.class})//只在修改时进行验证
    private String logo;
}

/**
 * 接口开启验证并指定分组
 */
 @PutMapping("/save")
public R save(@Validated(value = {
    
    AddGroup.class}) @RequestBody TestEntity test) {
    
    //进行新增分组验证
   return R.ok();
}
Custom check

  When the provided verification annotations are not what we need, such as status 0 and 1, we can define the verification rules by ourselves

/**
 * 自定义校验注解
 * 校验状态
 * 只能是0或1
 */
@Documented
@Constraint(validatedBy = {
    
    ListValueConstraintValidator.class})//指定校验器
@Target({
    
    METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})//注解标注的位置
@Retention(RUNTIME)//注解的作用域
public @interface ListValue {
    
    
    //错误信息,是从配置文件中获取的,也可以直接在这里定义
    String message() default "{com.peach.common.annotation.ListValue.message}";
    //分组
    Class<?>[] groups() default {
    
    };
    //负载信息
    Class<? extends Payload>[] payload() default {
    
    };
    //注解的值
    int[] vals() default {
    
    };
}

/**
 *	错误信息的配置
 *	ValidationMessages.properties
 */
com.peach.common.annotation.ListValue.message=必须提交指定的值

/**
 *  自定义校验器
 */
public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {
    
    
    private Set<Integer> set = new HashSet<>();
    /**
     * 初始化
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {
    
    
        int[] vals = constraintAnnotation.vals();//值
        for (int val : vals) {
    
    
            set.add(val);
        }
    }
    /**
     * 是否校验成功
     * @param value 提交的值
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
    
    
        return set.contains(value);
    }
}

Guess you like

Origin blog.csdn.net/weixin_45481406/article/details/111566017