Use of spring boot parameter validation (validator)
1, Introduction to validator
Bean Validation is a set of annotation based data validation specifications defined by Java. At present, it has been upgraded from version 1.0 of JSR 303 to version 1.1 of JSR 349 and then to version 2.0 of JSR 380 (2.0 was completed on August 2017). It has gone through three versions. It should be noted that JSR is only a standard. It specifies some specifications for verifying annotations, but it has not been implemented, such as @ Null, @ NotNull, @ Pattern, etc., which are located under the package javax.validation.constraints. hibernate validator implements this specification and adds some other verification annotations, such as @ NotBlank, @ NotEmpty, @ Length, etc., which are located in the package org.hibernate.validator.constraints
If Spring Boot is used in our project, the hibernate validator framework has been integrated into Spring Boot starter web, so there is no need to add other dependencies. If it is not a Spring Boot project, you need to add the following dependencies.
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.8.Final</version> </dependency>
2, Annotation introduction
Built in annotation
annotation | explain |
---|---|
@Null | The annotated element must be null |
@NotNull | Annotated element cannot be null |
@AssertTrue | The annotated element must be true |
@AssertFalse | The annotated element must be false |
@Min(value) | The annotated element must be a number and its value must be greater than or equal to the specified minimum value |
@Max(value) | The annotated element must be a number and its value must be less than or equal to the specified maximum value |
@DecimalMin(value) | The annotated element must be a number and its value must be greater than or equal to the specified minimum value |
@DecimalMax(value) | The annotated element must be a number and its value must be less than or equal to the specified maximum value |
@Size(max,min) | 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 an acceptable range |
@Past | The annotated element must be a past date |
@Future | The annotated element must be a future date |
@Pattern(value) | The annotated element must conform to the specified regular expression |
Extended annotation
annotation | explain |
---|---|
@NotBlank | The annotated element cannot be null, and the length must be greater than 0. It can only be used for annotation strings |
The annotated element must be an email address | |
@Length(min=,max=) | The size of the annotated string must be within the specified range |
@NotEmpty | The annotated element value is not null and empty. String, collection, Map and array types are supported |
@Range | The annotated element must be within the specified range |
3, Use of validator
Create verification tool class
package com.hl.springbootvalidator.util; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.hl.springbootcommon.exception.ParamException; import org.apache.commons.collections.MapUtils; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.*; public class BeanValidatorUtil { private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); //Return map public static <T> Map<String,String> validate(T t, Class... groups){ Validator validator=VALIDATOR_FACTORY.getValidator(); Set validateResult=validator.validate(t,groups); //If empty if (validateResult.isEmpty()){ return Collections.emptyMap(); }else{ //Not null indicates an error LinkedHashMap errors= Maps.newLinkedHashMap(); //ergodic Iterator iterator=validateResult.iterator(); while (iterator.hasNext()){ ConstraintViolation violation=(ConstraintViolation) iterator.next(); errors.put(violation.getPropertyPath().toString(),violation.getMessage()); } return errors; } } //Return to list public static Map<String,String> validateList(Collection<?> collection){ //Check whether the basic collection is empty com.google.common.base.Preconditions.checkNotNull(collection); //Traverse collection Iterator iterator=collection.iterator(); Map errors; do { //If the next loop is null, it returns null directly if (!iterator.hasNext()){ return Collections.emptyMap(); } Object object=iterator.next(); errors=validate(object,new Class[0]); }while (errors.isEmpty()); return errors; } // Verify whether an object is legal public static Map<String,String> validateObject(Object first,Object... objects){ if (objects !=null && objects.length > 0 ){ return validateList(Lists.asList(first,objects)); } else { return validate(first , new Class[0]); } } //Calibration parameter method public static void check(Object param) throws ParamException { Map<String,String> map= BeanValidatorUtil.validateObject(param); //If the error collection map is not empty, an exception is thrown if (MapUtils.isNotEmpty(map)){ throw new ParamException(map.toString()); } } }
Verify an object
@RestController @RequestMapping("/user") public class UserController { @PostMapping("/insert") public HttpResponseTemp<?> getUser2(@RequestBody UserParam userParam){ Map<String, String> map = BeanValidatorUtil.validateObject(userParam); if (MapUtils.isNotEmpty(map)){ throw ApiException.wrapMessage(ResultStat.SERVER_INTERNAL_ERROR,map.toString()); } return ResultStat.OK.wrap(map,"Verification complete"); }
@Data public class UserParam { private Integer id; @NotBlank(message = "User name cannot be empty") @Length(min = 1, max = 20, message = "The length of user name should be less than 20 words") private String username; @NotBlank(message = "Phone number cannot be empty") @Pattern(regexp = "^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$",message = "It can only be numbers") @Length(min = 1, max = 13, message = "The length of the phone should be less than 13 words") private String telephone; @NotBlank(message = "Mailbox cannot be empty") @Pattern(regexp = "^([a-zA-Z]|[0-9])(\\w|\\-)+@[a-zA-Z0-9]+\\.([a-zA-Z]{2,4})$",message = "The mailbox format is incorrect") @Length(min = 5, max = 50, message = "Mailbox length should be less than 50 characters") private String mail; @NotEmpty private List<Integer> lists; }
When the email format and phone number format are wrong
Object inline for verification
@Data public class UserParam { private Integer id; @NotBlank(message = "User name cannot be empty") @Length(min = 1, max = 20, message = "The length of user name should be less than 20 words") private String username; @NotBlank(message = "Phone number cannot be empty") @Length(min = 1, max = 13, message = "The length of the phone should be less than 13 words") private String telephone; @NotBlank(message = "Mailbox cannot be empty") @Length(min = 5, max = 50, message = "Mailbox length should be less than 50 characters") private String mail; @Valid private Phone phone; } @Data public class Phone { @NotBlank private String operatorType; @NotBlank private String phoneNum; }
@RestController @RequestMapping("/user") public class UserController { @PostMapping("/insert2") public HttpResponseTemp<?> getUser3(@RequestBody UserParam userParam){ Map<String, String> map = BeanValidatorUtil.validateObject(userParam); if (MapUtils.isNotEmpty(map)){ throw ApiException.wrapMessage(ResultStat.SERVER_INTERNAL_ERROR,map.toString()); } return ResultStat.OK.wrap(map,"Verification complete"); } }