Data verification (Validation)
Through Validator interface
Introduce related dependencies
<dependency> <groupId></groupId> <artifactId>hibernate-validator</artifactId> <version>7.0.</version> </dependency> <dependency> <groupId></groupId> <artifactId></artifactId> <version>4.0.1</version> </dependency>
Entity Class
@Data public class Person{ private String name; private String age; }
Data Verifier Class
public class PersonValidator implements Validator{ //Specify the type to be checked @Override public boolean supports(Class<?> clazz) { return (clazz); } //Calibration Rules @Override public void validate(Object target, Errors errors) { //name cannot be empty (errors,"name",errorCode:"","name is null") //<0age<100 Person p = (Person)target; if(()<0){ //The parameters are, the attributes, error codes, and prompt information that need to be checked. ("age","","age<0") }else if(()>100){ ("age","","age>100") } } }
Test class
@Test public void test(){ //Create a person object Person person = new Person(); ("li"); (-1); //Create a databinder corresponding to a person DataBinder binder = new DataBinder(person); //Set the checker (new PersonValidator()); //Calling method to perform verification (); //Output verification result BindingResult result = (); (()); }
Annotation via Validation
Configuration class, configure LocalValidatorFactoryBean
@Configuration @ComponentScan("") public class ValidationConfig{ @Bean public LocalValidatorFactoryBean validator(){ return new LocalValidatorFactoryBean(); } }
Entity Class
/** * Common annotations * @NotNull: Not empty * @NotEmpty: used for strings, strings are not empty, length is not 0 * @NotBlank: used for strings, strings are not empty, and after trim() they are not empty strings * @DecimalMax(value): Number not greater than the specified value * @DecimalMin(value): a number not less than the specified value * @Max(value): No greater than the specified value number * @Min(value): not less than the specified value number * @Pattern(value): Comply with the specified regular expression * @Size(max,min): The character length is between min and max * @Email: in email format */ @Component @Data public class User{ @NotNull private String name; @Min(0) @Max(100) private int age; public User(String name, int age){ =name; =age; } }
Verification device
//Native Verification Device@Service public class JavaValidation{ @Autowired private Validator validator; public boolean validatorByUser(User user){ Set<ConstraintViolation<User>> validate=(user); return (); } } //Spring's verification method@Service public class SpringValidation{ @Autowired private Validator validator; public boolean validatorByUser(User user){ BindException bindException = new BindException(user,()); (user,bindException); return (); } }
Test class
//Test the native checker@Test public void testJavaValidation(){ ApplicationContext context = new AnnotationConfigApplicationContext(); JavaValidation javaValidation = (); User user = new User("li",-1); boolean message = (user); (message); } //Test the spring checker@Test public void testJavaValidation(){ ApplicationContext context = new AnnotationConfigApplicationContext(); SpringValidation springValidation = (); User user = new User("li",-1); boolean message = (user); (message); }
Implement verification based on method
Configuration class
@Configuration @ComponentScan("") public class ValidationConfig{ @Bean public MethodValidationPostProcessor validationPostProcessor(){ return new MethodValidationPostProcessor(); } }
Entity Class
@Data public class User{ @NotNull private String name; @Min(0) @Max(100) private int age; public User(String name, int age){ =name; =age; } }
Verification device
@Service @Validated public class UserService{ public String testMethod(@NotNull @Valid User user){ return (); } }
Test class
@Test public void testJavaValidation(){ ApplicationContext context = new AnnotationConfigApplicationContext(); UserService service = (); User user = new User("li",-1); (user); }
Custom verification
Custom verification is actually to expand the existing verification function through custom annotations. Below, use verification without spaces as an example.
Custom annotations (can be changed directly into existing annotations)
@Target({,,ElementType.ANNOTATION_TYPE}) @Retention() @Documented @Constraint(validatedBy={}) public @interface CannotBlank{ //Default error message String message() default "cannot blank" Class<?>[] groups() default{}; Class<? extends Payload>[] payload() default{}; @Target({,,ElementType.ANNOTATION_TYPE}) @Retention() @Documented public @interface List{ NotNull[] value(); } }
Annotation parser
public class CannotBlankValidation implements ConstraintValidator<CannotBlank,String>{ @Override public boolean isValid(String value, ConstraintValidatorContext context){ if(value != null && (" ")){ return false; } } }
This is the end of this article about the data verification method in SpringFramework. For more related SpringFramework data verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!