SpringMVC parameter verification and springmvc Verification
Using spring MVC with hibernate-validate for parameter validity verification can save a certain amount of code.
Procedure
1. Build a Web project and introduce the hibernate-validate dependency
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.7.Final</version></dependency>
Maven dependency transmission, automatic dependency on validation-api, jboss-logging, classmate
2. Mark attributes with verification annotations (dto)
*Each annotation has the message attribute, which is used to fill in the exception description information when verification fails. When verification fails, the corresponding message attribute value can be obtained.
Public class User {@ NotNull (message = "id cannot be blank! ") Private Integer id; @ NotBlank (message =" the user name cannot be blank! ")
@ Size (min = 4, max = 12, message = "the length of the user name is 4 ~ Between 12! ") Private String username; @ NotBlank (message =" the password cannot be blank! ") Private String password; @ Email (message =" invalid Email! ") Private String email; public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password;} public String getEmail () {return email;} public void setEmail (String email) {this. email = email;} public User () {super ();}}
3. Use dto to receive parameters in the control layer and use @ Validated/@ Valid annotation to enable parameter verification.
*@ ValidatedAnnotation indicates that the Spring verification mechanism is used. group verification is supported and declared on the input parameter.
*@ ValidAnnotation indicates that the Hibernate verification mechanism is used, and group verification is not supported. It is declared on the input parameter.
*Keep up with dtoBindingResultObject used to obtain the exception information when verification fails.
@RestControllerpublic class BaseController { @RequestMapping("/test") public User test(@Validated User user, BindingResult result) { if (result.hasErrors()) { List<ObjectError> errors = result.getAllErrors(); for (ObjectError error : errors) { System.out.println(error.getDefaultMessage()); } } return user; }}
Demo:
Result:
The password cannot be blank! Id cannot be blank! The length of the user name is 4 ~ Between 12!
*The Check order is random, so the program cannot rely on the check order for relevant logic processing.
4. group verification
EachVerification AnnotationAll haveGroupAttribute is used to specify the group to which the validation belongs. Its value is a Class array, which is used in the Controller@ ValidatedWhen parameter verification is enabled for AnnotationWhenIf you specify the group to be verified, only the same attributes of the Group will be verified (full match by default ).
Class<?>[] groups() default { };
Generally, the ID interface is defined as a group resource.
public interface GroupA {}public interface GroupB {}
Mark and group attributes with verification annotations
Public class User {@ NotNull (message = "id cannot be blank! ", Groups = {GroupA. class}) private Integer id; @ NotBlank (message =" the user name cannot be blank! ", Groups = {GroupB. class}) @ Size (min = 4, max = 12, message =" the length of the user name is 4 ~ Between 12! ") Private String username; @ NotBlank (message =" the password cannot be blank! ") Private String password; @ Email (message =" invalid Email! ") Private String email; public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password;} public String getEmail () {return email;} public void setEmail (String email) {this. email = email;} public User () {super ();}}
In Controller, the @ Validated annotation is used to enable parameter verification and specify the verification group. Only the same attributes of the group are verified (full match by default ),
@RestControllerpublic class BaseController { @RequestMapping("/test") public User test(@Validated(value= {GroupB.class}) User user, BindingResult result) { if (result.hasErrors()) { List<ObjectError> errors = result.getAllErrors(); for (ObjectError error : errors) { System.out.println(error.getDefaultMessage()); } } return user; }}
Demo:
Result:
The user name cannot be blank!