Defining annotations
Implement a constraint that can only enter a specified state
ImportJavax.validation.Constraint;ImportJavax.validation.Payload;Importjava.lang.annotation.Documented;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.Target;Import StaticJava.lang.annotation.ElementType.ANNOTATION_TYPE;Import StaticJava.lang.annotation.ElementType.FIELD;Import StaticJava.lang.annotation.ElementType.METHOD;Import StaticJava.lang.annotation.RetentionPolicy.RUNTIME; @Target ({METHOD, FIELD, Annotation_type}) @Retention (RUNTIME) @ Constraint (Validatedby= Statusvalidator.class) @Documented Public@Interfacevalidstatus {String message ()default"Status Error"; Class<?>[] Groups ()default {}; Class<?extendsPayload>[] Payload ()default {}; /*** Valid set of status values, default {*/ int[] Value ()default{};}
Defining a validation class
ImportJavax.validation.ConstraintValidator;ImportJavax.validation.ConstraintValidatorContext;Importjava.util.Arrays;Importjava.util.List;/*** Verify whether the state belongs to the specified state set (the type of the generic object specified after Constraintvalidator is the type of the annotation class and the annotation comment field <validstatus, integer>)*/ Public classStatusvalidatorImplementsConstraintvalidator<validstatus, integer> { Privateinteger[] Validstatus; @Override Public voidInitialize (Validstatus validstatus) {int[] INTs =Validstatus.value (); intn =ints.length; integer[] Integers=NewInteger[n]; for(inti = 0; I < n; i++) {Integers[i]=Ints[i]; } This. Validstatus =integers; } @Override Public BooleanIsValid (Integer N, Constraintvalidatorcontext constraintvalidatorcontext) {List<Integer> status =arrays.aslist (validstatus); if(Status.contains (n)) {return true; } return false; }}
Used in programs
Public classquerydto {@ValidStatus @notnullPrivateInteger type;//... Omit n lines of code} @RestController @requestmapping (value= "XXX") Public classDemocontroller {//... Omit n lines of code@PostMapping (value = "/testurl") PublicResponse<resultvo>getxxxlist (@RequestBody @Valid querydto dto) {//... Omit n lines of code } }
You can also use this:
Validatorfactory factory = validation.builddefaultvalidatorfactory (); = factory.getvalidator (); Set<ConstraintViolation<QueryDTO>> constraintviolations = validator.validate (querydto);
Customizing Hibernate validator Constraints