参数校验注解的使用

参数校验注解的使用

校验注解,用于要验证参数对象中的属性上,以实现提交数据的验证。避免另外写代码来验证参数是否规范,以达到高复用目的。

一、常用校验注解

	注解					说明
----------------------------------------------------
	@NotNull			属性不能为null
	@NotEmpty			集合不能为null,且size大于0
	@NotBlanck			字符类不能为null,且去掉空格之后长度大于0
	@AssertTrue			布尔属性必须是true
	@Min				限定数字的最小值(整型)
	@Max				限定数字的最大值(整型)
	@DecimalMin			限定数字的最小值(字符串,可以是小数)
	@DecimalMax			限定数字的最大值(字符串,可以是小数)
	@Range				限定数字范围(长整型)
	@Length				限定字符串长度
	@Size				限定集合大小
	@Digits				必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
	@Negative			该值必须小于0
	@NegativeOrZero		该值必须小于等于0
	@Past				必须是一个过去的时间或日期
	@PastOrPresent		必须是一个过去或现在的日期
	@Future				必须是一个未来的时间或日期
	@FutureOrPresent	必须是一个现在或将来的日期
	@Email				必须是一个邮箱格式
	@Pattern			正则匹配字符串
	@Positive			必须大于0
	@PositiveOrZero	    必须大于等于0

以上注解框架已实现,可引用后直接使用。

二、使用方式:

参数对象,在对应属性上定义Validator:

public class Test {

    @NotNull(message = "ID不能为空")
    @Range(min = 1, max = 100, message = "ID必须在1到100之间")
    private Integer id;

    @NotBlank(message = "姓名不能为空")
    @Length(min = 2, max = 6, message = "姓名必须在2到6位之间")
    private String name;

    @NotNull(message = "余额不能为空")
    @DecimalMax(value = "30.50", message = "余额不能超过30.5")
    @DecimalMin(value = "1.50", message = "余额不能低于1.5")
    private BigDecimal amount;

    @NotNull(message = "生日不能为空")
    @Past(message = "生日必须是过去")
    private Date birthday;

    @NotBlank(message = "邮箱不能为空")
    @Email(message = "邮箱格式不正确")
    private String email;

    @NotBlank(message = "手机号不能为空")
    @Pattern(regexp = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\\d{8})$", message = "手机号格式错误")
    private String phone;

}

在 Controller 中使用:

@PostMapping("/test")
@ApiOperation(value = "测试", notes = "", response = Result.class)
public Result test(@ApiParam(name = "test", value = "参数", required = true) @Validated @RequestBody Test test, BindingResult bindingResult) {
    if(bindingResult.hasErrors()){
        String errorMsg = bindingResult.getFieldError().getDefaultMessage();
        return Result.error(errorMsg);
    }
    return Result.ok("参数验证通过");
}

说明:

  1. 使用用 @Validated 指定 test 这个参数是需要校验的。

  2. 使用 bindingResult 来接收校验结果。

     if(bindingResult.hasErrors()){
    
     	String errorMsg = bindingResult.getFieldError().getDefaultMessage();
     	return Result.error(errorMsg);
     }
    

三、自定义校验注解

当原有的校验注解不能满足使用需求时,可通过实现 ConstraintValidator 接口,实现自定义校验注解。

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
        validatedBy = {IsMobileValidator.class}
)
public @interface IsMobile {
 
    boolean required() default true;
 
    String message() default "手机号格式不正确";
 
    Class<?>[] groups() default {};
 
    Class<? extends Payload>[] payload() default {};
}

说明:

IsMobile类为自定义注解,该自定义注解类中用到了四种元注解,最后一个@Constraint指定了校验类,也就是接下来的IsMobileValidator类。值得一提的是除了自定义的 message、require 属性外,下面的 groups和payload 也是必须添加的。

public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {

    private boolean require = false;
 
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        require = constraintAnnotation.required();
    }
 
    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if(require){
            return ValidatorUtils.isMobile(s);
        }else {
           if (StringUtils.isEmpty(s)) {
               return true;
           }else {
               return ValidatorUtils.isMobile(s);
           }
        }
    }
} 

校验类需要实现ConstraintValidator接口。
接口使用了泛型,需要指定两个参数,第一个自定义注解类,第二个为需要校验的数据类型。
实现接口后要override两个方法,分别为 initialize 方法和 isValid 方法。其中initialize为初始化方法,可以在里面做一些初始化操作,isValid方法就是我们最终需要的校验方法了。可以在该方法中实现具体的校验步骤。

完成这几部分之后,一个简单的自定义校验注解就完成啦,不要忘记在使用的时候加上@Valid注解开启valid校验。

部分内容摘抄自:https://blog.csdn.net/qq_38439885/article/details/81227063

posted @ 2019-05-20 11:25  合法勒索夫  阅读(948)  评论(0)    收藏  举报