JAVA项目中使用JSR303数据校验

  1. 给Bean添加校验注解:javax.validation.constraints,并定义自己的message提示
    需要引入依赖
		
        
            javax.validation
            validation-api
            1.1.0.Final
        
        
        
        
            org.hibernate
            hibernate-validator
            5.2.0.Final
        

下面的hibernate validator在URL校验的时候会用到

  1. 开启校验功能@Valid
	@RequestMapping("/save")
    public R save(@Valid @RequestBody BrandEntity brand, BindingResult result) {
        brandService.save(brand);
        return R.ok();
    }

效果:校验错误以后会有默认的响应

  1. 给校验的bean后紧跟一个BindingResult, 就可以获取到校验的结果
import com.common.valid.AddGroup;
import com.common.valid.UpdateGroup;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;
@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;
    /**
     * 品牌名
     */
    @NotNull(message = "品牌名必须提交", groups = {UpdateGroup.class, AddGroup.class})
    private String name;
    /**
     * 品牌logo地址
     */
    @NotNull(groups = AddGroup.class)
    @URL(message = "logo必须是一个合法的url地址", groups = {UpdateGroup.class, AddGroup.class})
    private String logo;
    /**
     * 介绍
     */
    private String descript;
    /**
     * 显示状态[0-不显示;1-显示]
     */
    private Integer showStatus;
    /**
     * 检索首字母
     */
    @NotNull(groups = {AddGroup.class})
    @Pattern(regexp = "/^[a-zA-Z]$/", message = "检索首字母必须是一个字母", groups = {UpdateGroup.class, AddGroup.class})
    private String firstLetter;
    /**
     * 排序
     */
    @NotNull(groups = {AddGroup.class})
    @Min(value = 0, message = "排序必须大于等于0", groups = {UpdateGroup.class, AddGroup.class})
    private Integer sort;

}
  1. 分组校验

1)、@NotBlank(message = “品牌名必须提交”, groups = {AddGroup. class, UpdateGroup. class})
给校验注解标注什么情祝需要进行校验
创建空接口就行

public interface AddGroup {
}

2)、@Validated( {AddGroup.class})

@RequestMapping("/save")
    //@RequiresPermissions("product:brand:save")
    public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand/*, BindingResult result*/) {
//        if (result.hasErrors()) {
//            Map map = new HashMap<>();
//            //获取校验的错误结果
//            result.getFieldErrors().forEach((item) -> {
//                //FieldError获取到错误提示
//                String message = item.getDefaultMessage();
//                //获取错误的属性名字
//                String field = item.getField();
//                map.put(field, message);
//            });
//            return R.error(400, "提交的数据不合法").put("data", map);
//        } else {
//            brandService.save(brand);
//        }
        brandService.save(brand);
        return R.ok();
    }

3)、默认没有指定分组的校验注解@NotBlank,在分组校验情况下不生效

  1. 自定义校验
	/**
     * 显示状态[0-不显示;1-显示]
     */
    @ListValue(vals={0,1})
    private Integer showStatus;

然后编写ListValue

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {})
public @interface ListValue {
    String message() default "{com.atguigu.common.valid.ListValue.message}";

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

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

    int[] vals() default {};
}

编写配置文件
路径:resources/ValidationMessages.properties

com.atguigu.common.valid.ListValue.message=必须提交指定的值

写实现方法

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

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

然后为了让他们产生关联,在前面

public @interface ListValue

的注解中添加

@Constraint(validatedBy = { ListValueConstraintValidator.class })

完整代码如下

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = { ListValueConstraintValidator.class })
public @interface ListValue {
    String message() default "{com.atguigu.common.valid.ListValue.message}";

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

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

    int[] vals() default {};
}

测试
JAVA项目中使用JSR303数据校验_第1张图片

你可能感兴趣的:(java)