谷粒商城项目总结--JSR303数据校验

分组校验需要指定groups 需要@Validated 需要创建相应的接口
设置不同分组可以设置不同状态下的校验规则

//接口什么都不用写 创建就行
public interface UpdateGroup {}
public interface AddGroup{}
	@NotNull(message = "修改必须指定ID",groups = {UpdateGroup.class})
	@Null(message = "新增不能指定ID",groups = {AddGroup.class})
	@TableId
	private Long brandId;

参数加上 @Valid(不支持分组) 或 @Validated 注解

    @RequestMapping("/save")
    public R save(@Validated(AddGroup.class) @RequestBody BrandEntity brand BindingResult result){
        if (result.hasErrors()){
            System.out.println("HAS ERROR====================");
            Map<String, String> map = new HashMap<>();
            result.getFieldErrors().forEach(item -> {
                String message = item.getDefaultMessage();//错误消息
                String field = item.getField();//错误的属性名字
                map.put(field,message);
            });
            return R.error(400,"提交的数据不合法").put("data",map);
        }
		brandService.save(brand);
        return R.ok();
    }

常用校验

@NotNull
@Null
@NotBlank
@NotEmpty
@URL
@Pattern(regexp = "^[a-zA-Z]$",message = "检索首字母必须是英文字母")
@Min

自定义校验注解

//新建Annotation CustomAnnotation
@Documented
@Constraint(validatedBy = {CustomConstraintValidator.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
public @interface CustomAnnotation {
    String message() default "{com.atguigu.common.valid.CustomAnnotation.message}";

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

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

    int[] value() default {};
}
//实现CustomAnnotation
public class CustomConstraintValidator implements ConstraintValidator<CustomAnnotation,Integer>{
    private Set<Integer> set = new HashSet<>();

    //初始化方法
    @Override
    public void initialize(CustomAnnotation constraintAnnotation) {
        int[] value = constraintAnnotation.value();
        for (int val : value) {
            set.add(val);
        }
    }
    /**
     * @Description   //判断是否校验成功
     * @Param value: 需要校验的值
     * @Param context:
     * @return boolean
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return set.contains(value);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值