SpringBoot自定义参数校验

SpringBoot自定义参数校验

@Data
public class User implements Serializable {
    // 自定义校验,验证 username 必须以a开头,长度为5
    @ValName
    private String username;
    @NotNull
    private Integer age;
    @ValName(require = false,message = "str不能为空")
    private String str;
}

点进 @NotNull的源码,复制过过来就行

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(NotNull.List.class)
@Documented
@Constraint(
    validatedBy = {}
)
public @interface NotNull {
    String message() default "{javax.validation.constraints.NotNull.message}";

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

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

    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface List {
        NotNull[] value();
    }
}

复制到我们自己的注解

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = ValNameValidator.class)//自定义的参数校验类
public @interface ValName {
    boolean require() default true;
    String message() default "名称不符合规范,只能以a开头,长度为5";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

自定义参数校验类ValNameValidator,实现ConstraintValidator

public class ValNameValidator implements ConstraintValidator<ValName, String> {
    // 保存 require的值,获取到注解中的
    boolean require = true;
    @Override
    public void initialize(ValName constraintAnnotation) {
        this.require = constraintAnnotation.require();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        // a开头,长度为5
        if (require) {
            if (value.charAt(0) == 'a' && value.length() == 5) {
                return true;
            }
        } else {
            //不需要就验证,有值就行
            if (!StringUtils.isEmpty(value)) {
                return true;
            }
        }
        return false;
    }
}

controller使用

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/login")
    public String login(@Valid User user, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return bindingResult.getFieldError().getDefaultMessage();
        }
        return user.toString();
    }
}

错误:
在这里插入图片描述
正确:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值