SpringBoot + Thymeleaf + Validate verification,
During business development, it is inevitable that some verification needs to be processed. if you write the if-else code for verification, there will be a large segment of such code. But fortunately, there is a validation plug-in: javax. validation. validation-api, But it generally references the hibernate validation component: org. hibernate. hibernate-validator, which has referenced the validation-api component.
1. Basic verification type
JSR303 is a set of JavaBean Parameter validation standard, which defines many common verification annotations. We can directly add these annotations to the attributes of our JavaBean, you can perform the verification when the verification is required. Note:
Create an object class to be verified, and use some common verification annotations, which is easy to understand. The verification content can be inferred by the annotation name on the field, each annotation contains the message field, which is used as a prompt when verification fails,
For special verification annotations, such as Pattern (Regular Expression verification), you can also add a regular expression and add @ notnull @ size to the object class for verification. For example:
1 @ Entity 2 @ Table (name = "userinfo", uniqueConstraints = @ UniqueConstraint (columnNames = "username") 3 public class User {4 private Integer id; 5 @ Size (min = 4, max = 15, message = "username length: 4-15 characters") 6 private String username; 7 @ Size (min = 6, max = 18, message = "password 6-18 characters") 8 private String password; 9 @ Pattern (regexp = "^ ([a-z0-9A-Z] + [-| \.]?) + [A-z0-9A-Z] @ ([a-z0-9A-Z] + (-[a-z0-9A-Z] + )? \\.) + [A-zA-Z] {2,} $ ", message =" Incorrect email format ") 10 private String email; 11 @ Pattern (regexp = "^ (13 [0-9]) | (15 [^ 4, \ D]) | (18 [0, 5-9]) \ d {8} $ ", message =" Incorrect mobile phone number ") 12 private String phone; 13 @ NotEmpty (message =" gender cannot be blank ") 14 private String sex; 15 private Date creat_time; 16 private Date update_time; 17 @ Id18 @ GeneratedValue19 public Integer getId () {20 return id; 21}
// Omit the following set and get Methods
Note:
@ Null the annotated element must be null.
@ Notnull the annotated element must not be blank
@ AssertTrue the annotated element must be true
@ AssertFalse the annotated element must be false.
@ Min the annotated element must be a number whose value must be greater than or equal to the specified minimum number.
@ Max the annotated element must be a number whose value must be less than or equal to the specified maximum number.
@ DecimalMin the annotated element must be a number whose value must be greater than or equal to the specified minimum number.
@ DecimalMax the annotated element must be a number and its value must be smaller than or equal to the specified maximum number.
@ Size (min, max) the Size of the annotated element must be within the specified range.
@ Digits (integer, fraction) The annotated element must be a number and its value must be within the acceptable range.
@ Past the annotated element must be a previous date
@ Future the annotated element must be a Future date
@ Pattern (value) The annotated element must conform to the specified regular expression.
@ Email the annotated element must be an Email address.
@ Length the size of the commented string must be within the specified range
@ NotEmpty the annotated string must be non-empty
@ Range the annotated element must be within the appropriate Range.
@ NotNull and @ NotEmpty are different from @ NotBlank:
@ NotEmpty is used on the Collection class, @ NotBlank is used on the String, @ NotNullUsed in the basic type.
We can see that we have added an annotation on the get method corresponding to username, password and age, These annotations are the limitation defined in the JSR-303, put the corresponding validation error information in the Errors object of Spring.
2. Verify data in @ Controller
Next we will define a Controller that uses the User object as the parameter receiver. The Code is as follows:
1 @Controller 2 public class FooController { 3 @RequestMapping("/foo") 4 public String foo(@Validated Foo foo <1>, BindingResult bindingResult <2>) { 5 if(bindingResult.hasErrors()){ 6 for (FieldError fieldError : bindingResult.getFieldErrors()) { 7 //... 8 } 9 return "fail";10 }11 return "success";12 }13 }
<1> Add the @ Validated annotation before the Foo parameter, indicating that spring needs to verify it, and the verification information will be stored in the BindingResult. Note: It must be adjacent. If multiple parameters need to be verified, the format can be as follows. Foo (@ Validated Foo, BindingResult fooBindingResult, @ Validated Bar, BindingResult barBindingResult) {// ***}; that is, a verification class corresponds to a verification result.
<2> the verification result is automatically filled. In the controller, you can decide the specific operation based on the business logic. For example, you can jump to the error page.
3. Get error information in message on the page
Now, add the Object to th: Object in Form, and use # fields. hasErrors ('field name') determines whether the field has an error. If there is an error, Use th: errors = "* {field name}" to display the error message in messages. For example:
<p th:if="${#fields.hasErrors('username')} " th:errors="*{username}" class="text-danger"></p>
4. group verification
For example:
1 Class Foo{2 @Min(value = 18,groups = {Adult.class})3 private Integer age;4 public interface Adult{}5 public interface Minor{}6 }
The age in this example is verified only in the Adult group. For example:
1 @RequestMapping("/drink")2 public String drink(@Validated({Foo.Adult.class}) Foo foo, BindingResult bindingResult) {3 if(bindingResult.hasErrors()){4 for (FieldError fieldError : bindingResult.getFieldErrors()) {}......
5. Custom Verification
(1) We try to add a "string cannot contain spaces" restriction.
1 @ Target ({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER}) 2 @ Retention (RUNTIME) 3 @ incluented 4 @ Constraint (validatedBy = {cannothaveblkvalidator. class}) <1> 5 public @ interface CannotHaveBlank {6 // default error message 7 String message () default "cannot contain spaces"; 8 // group 9 Class <?> [] Groups () default {}; 10 // load 11 Class <? Extends Payload> [] payload () default {}; 12 // when multiple objects are specified, use 13 @ Target ({FIELD, METHOD, PARAMETER, ANNOTATION_TYPE}) 14 @ Retention (RUNTIME) 15 @ Documented16 @ interface List {17 CannotHaveBlank [] value (); 18} 19}
We don't need to pay attention to much. The principle of using spring validation is convenient for our development, such as payload, List, and groups.
<1> the real verifier class of the annotation is specified in the Custom annotation.
(2) Compile a real validator class
1 public class implements <1> ConstraintValidator <CannotHaveBlank, String> {2 @ Override 3 public void initialize (constraint constraintAnnotation) {4} 5 @ Override 6 public boolean isValid (String value, constraintValidatorContext context <2>) {7 // if null, 8 if (value! = Null & value. contains ("") {9 <3> 10 // obtain the default message 11 String defaultConstraintMessageTemplate = context. getdefaconconstraintmessagetemplate (); 12 System. out. println ("default message:" + defaultConstraintMessageTemplate); 13 // disable the default message 14 context. disableDefaultConstraintViolation (); 15 // sets the prompt language 16 context. buildConstraintViolationWithTemplate ("can not contains blank "). addConstraintViolation (); 17 return false; 18} 19 return true; 20} 21}
<1> All validators must implement the ConstraintValidator interface. Its interface is also very visual, including an initialization event method and a method to determine whether the method is valid.
1 public interface ConstraintValidator<A extends Annotation, T> {2 3 void initialize(A constraintAnnotation);4 5 boolean isValid(T value, ConstraintValidatorContext context);6 }
<2> ConstraintValidatorContext contains all authentication information. You can use this context to obtain the default error message, disable the error message, and modify the error message.
<3> some typical verification operations may inspire you.
It is worth noting that the custom annotation can be used on METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, and PARAMETER. The second generic parameter t of ConstraintValidator is the type to be verified.