Springboot uses JSR303 to verify the submitted parameters, including group verification and custom verification

Directory structure for parameter verification:
Insert picture description here

1. If we want to verify the incoming parameters, we only need to use annotations on the entity class passed in by the receiving front end.

/**
 * 品牌
 *
 * @date 2019-10-01 21:08:49
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
    
    
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@NotNull(message = "修改必须指定品牌id",groups = {
    
    UpdateGroup.class})//只有在修改的时候才会触发
	@Null(message = "新增不能指定id",groups = {
    
    AddGroup.class})//只有在新增的时候才会触发
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 */
	@NotBlank(message = "品牌名必须提交",groups = {
    
    AddGroup.class,UpdateGroup.class})
	private String name;
	/**
	 * 品牌logo地址
	 */
	@NotBlank(groups = {
    
    AddGroup.class})
	@URL(message = "logo必须是一个合法的url地址",groups={
    
    AddGroup.class,UpdateGroup.class})
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
//	@Pattern()
	@NotNull(groups = {
    
    AddGroup.class, UpdateStatusGroup.class})
  	@ListValue(vals={
    
    0,1},groups = {
    
    AddGroup.class, UpdateStatusGroup.class})
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	@NotEmpty(groups={
    
    AddGroup.class})
	@Pattern(regexp="^[a-zA-Z]$",message = "检索首字母必须是一个字母",groups={
    
    AddGroup.class,UpdateGroup.class})
	private String firstLetter;
	/**
	 * 排序
	 */
	@NotNull(groups={
    
    AddGroup.class})
	@Min(value = 0,message = "排序必须大于等于0",groups={
    
    AddGroup.class,UpdateGroup.class})
	private Integer sort;

}

2. Group verification:
Add the AddGroup grouping interface, there is no need to write anything in it.

public interface AddGroup {
    
    
}

Add UpdateGroup group interface, there is no need to write anything in it.

public interface UpdateGroup {
    
    
}

The brandId field does not need to pass this parameter when adding data, but it needs to be passed when modifying.
Then add an annotation
@Validated({AddGroup.class} to the new method of the corresponding Controller

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@Validated({
    
    AddGroup.class}) @RequestBody BrandEntity brand) {
    
    
        brandService.save(brand);
        return R.ok();
    }

Add an annotation
@Validated({UpdateGroup.class} to the modification method of the corresponding Controller

	/**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@Validated({
    
    UpdateGroup.class}) @RequestBody BrandEntity brand) {
    
    
        brandService.updateById(brand);
        return R.ok();
    }

3. Custom verification:
Take @ListValue(vals={0,1}
private Integer showStatus above the field showStatus as an example.
1. Write a custom verification annotation
2. Write a custom validator ConstraintValidator
3. Associate a custom validator and a custom validation annotation


Add maven dependency

 <dependency>
     <groupId>javax.validation</groupId>
     <artifactId>validation-api</artifactId>
     <version>2.0.1.Final</version>
 </dependency>

Write a custom verification annotation

@Documented
@Constraint(validatedBy = {
    
     ListValueConstraintValidator.class })//关联自定义的校验器
@Target({
    
     METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
public @interface ListValue {
    
    
    String message() default "{ListValue.message}";

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

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

    int[] vals() default {
    
     };
}

Write a custom validator ConstraintValidator

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 需要校验的值
     * @param context
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
    
    
        return set.contains(value);
    }
}

Guess you like

Origin blog.csdn.net/u014496893/article/details/113728850