Custom hibernate backend parameter validation annotations

I want to verify the front end of the incoming object Integer property

1. Create a new annotation class @FlagValidator

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

/**
 * User authentication status is within a specified range of notes
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER})
@Constraint(validatedBy = FlagValidatorClass.class)
public @interface FlagValidator {
    String[] value() default {};

    String message() default "flag is not found";

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

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

2. Create a new class that inherits achieve ConstraintValidator

 

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Description TODO
 * @Author xjy
 * @Date 2019/9/29
 */
public class FlagValidatorClass implements ConstraintValidator<FlagValidator, Integer> {

    private String[] values;

    @Override
    public void initialize(FlagValidator flagValidator) {
        values = flagValidator.value();
    }
   // The following decision logic, values ​​which are annotated value, value is the value of the property
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
        boolean isValid = false;
        if (value == null){
            return true;
        }
        for (int i = 0; i < values.length; i++) {
            if (values[i].equals(String.valueOf(value))){
                isValid = true;
                break;
            }
        }
        return isValid;
    }
}

3. Use

  @FlagValidator (value = { "1", "5"}, message = "Please enter the correct state")
  private Integer status = 1;

  

Guess you like

Origin www.cnblogs.com/418836844qqcom/p/11640810.html