How to customize the simple verification annotation based on JSR303 in SpringBoot

1. Environment

  • SpringBoot 2.2.2.RELEASE
  • Dependency validation-api(here is only the dependency of introducing the function)
 	 <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

2. Write a custom inspection annotation

  • To write a @interfaceclass, I use ValidValue as an example here.
  • The following three are required JSR303in the regulations
	// 校验不通过时返回的错误信息
    String message() default "The specified value must be submitted";
	// 在需要多个校验规则的时候可以指定是哪个组的校验规则
    Class<?>[] groups() default {
    
    };
	//
    Class<? extends Payload>[] payload() default {
    
    };
  • The set rules are the rules int[] vals() default {};you want to use for verification. This means that the number you enter must be in the array.
  • The complete example is as follows ( if you don't know what the annotations on the class use, you can just click in a check annotation and copy it )
  • The ValidValueConstraintValidatorvalidator inside (described below) needs to be bound to your validation annotations
/**
 * @Author: llzhyaa 
 * @Date: 2020/4/10 21:05
 * validatedBy = {} 可以指定多个校验器
 */
@Documented
@Constraint(
        validatedBy = {
    
    ValidValueConstraintValidator.class}
)
@Target({
    
    ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidValue{
    
    
    // 这三个是必须有的
    String message() default "The specified value must be submitted";

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

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

    int[] vals() default  {
    
    };
}

3. Write a custom validator

  • Need to define a validator
  • A extends Annotation 指定注解 (就是你上面自定义注解的名字)
  • T 指定类型 ,就是你需要校验的变量的类型
/**
 * @Author: llzhyaa 
 * @Date: 2020/4/10 21:15
 * 校验器
 * ConstraintValidator<A extends Annotation, T>
 *     A extends Annotation 指定注解 (就是你上面自定义注解的名字)
 *     T 指定类型 
 */
public class ValidValueConstraintValidator implements ConstraintValidator<ValidValue,Integer> {
    
    

    private Set<Integer> set = new HashSet<>();

    @Override
    public void initialize(ValidValue constraintAnnotation) {
    
    
        // 初始化 , 获取到在你注解上的数字,存入一个set中
        int[] vals = constraintAnnotation.vals();
        if(vals  != null){
    
    
          for (int val : vals) {
    
    
            set.add(val);
       		 }
        }	
    }

    // 判断是否校验成功

    /**
     *
     * @param integer 需要校验的值(就是你传入的值)
     * @param constraintValidatorContext
     * @return
     */
    @Override
    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
    
    
		// 校验,获取到你输入的数字是否包含在你之前的set中
        return set.contains(integer);
    }
}
  • Associate a custom checker with a custom check annotation
  • That is to @Constraintbind your custom validator on your custom validation annotation
@Constraint(
      validatedBy = {
    
    ValidValueConstraintValidator.class}
)

4. Add a comment on your controller

  • @ValidIndicates that the incoming value needs to be verified
  • BindingResult result, You can get the error information
	@ResponseBody
    @RequestMapping("/test")
    public Map<String,String> test(@Valid String showStatus ,BindingResult result){
    
    
       if (result.hasErrors()){
    
    
            // 获取错误结果
            Map<String,String> map = new HashMap<>();
            result.getFieldErrors().forEach((item)->{
    
    
                // FieldError 获取错误提示
                String message = item.getDefaultMessage();
                String field = item.getField();
                map.put(field,message);
            })
        }
        return map ;
    }

4. Test

  • Just add your annotations to the variables you need to verify
  • @ValidValue(vals = {0,1}), Which means that the number you enter must be 0 or 1. If it is another number, an error will be reported
	@ValidValue(vals = {
    
    0,1})
	private Integer showStatus;
  • Just look at the details of the error,
 	{
    
    
   		 // 这里就是你自定义的默认返回错误
        "showStatus": "The specified value must be submitted",
    }

5. How to customize the error message returned

  • In the comments provided by the jar package, their error messages are all placed in the jar package, which can be seen by ValidationMessages.propertiesglobal search ValidationMessages.
  • E.g
javax.validation.constraints.AssertFalse.message     = must be false
javax.validation.constraints.AssertTrue.message      = must be true
javax.validation.constraints.DecimalMax.message      = must be less than ${
    
    inclusive == true ? 'or equal to ' : ''}{
    
    value}
javax.validation.constraints.DecimalMin.message      = must be greater than ${
    
    inclusive == true ? 'or equal to ' : ''}{
    
    value}
javax.validation.constraints.Digits.message          = numeric value out of bounds (<{
    
    integer} digits>.<{
    
    fraction} digits> expected)
javax.validation.constraints.Email.message           = must be a well-formed email address
javax.validation.constraints.Future.message          = must be a future date
javax.validation.constraints.FutureOrPresent.message = must be a date in the present or in the future
javax.validation.constraints.Max.message             = must be less than or equal to {
    
    value}
javax.validation.constraints.Min.message             = must be greater than or equal to {
    
    value}
javax.validation.constraints.Negative.message        = must be less than 0
javax.validation.constraints.NegativeOrZero.message  = must be less than or equal to 0
javax.validation.constraints.NotBlank.message        = must not be blank
javax.validation.constraints.NotEmpty.message        = must not be empty
javax.validation.constraints.NotNull.message         = must not be null
  • So we write a ValidationMessages.propertiesfile ourselves and put it in the resources directory
  • com.study.common.valid.ValidValue.messageIs your custom annotation plus.message
com.study.common.valid.ValidValue.message=输入的数字必须不规范
  • Then the default return information above your custom annotation needs to be modified
 String message() default "{com.study.common.valid.ListValue.message}";

Guess you like

Origin blog.csdn.net/JISOOLUO/article/details/105444344