in the RESTful interface service, there are various request parameters. Before jumping into the business processing phase, there is usually a basic data verification mechanism. After the verification is passed and the result is correct, the request parameters will be transferred to the formal business processing.
maven dependency introduction
in the Spring Boot project, two packages need to be introduced for Validation verification:
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.16.Final</version> <scope>compile</scope> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency>
How to use javax Validation @ valid annotation
hibernate validator is mainly used by adding @ Valid annotation to the request parameters of the Controller. It is "zero configuration" and can be used without configuration@ The Valid annotation indicates that the attribute of this object needs to be verified:
public String saveUser(@RequestBody **@Valid** User user) {...}
since it is attribute verification, there must be verification results. The verification results can be obtained by directly adding a BindingResult variable to the request parameters. Mark the following comments on the properties of the User class:
import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotBlank; /** * @author Wiener * @since 2021/11/7 */ @Data public class User { @NotBlank( message = "Name cannot be empty" ) @Length( message = "The maximum length of the name is {max}Characters" , min = 1 , max = 20 ) private String name; @NotBlank( message = "Password cannot be empty" ) @Length( message = "Password must be at least{min}Characters, max {max}Characters" , min = 8 , max = 30 ) private String password; /** Age */ @NotNull(message = "Please enter age") @Range(message = "The age range is {min} reach {max} between", min = 1, max = 150) public Integer age; @NotBlank @Size(max=32,message="address is null") private String address; /** * Current time cannot be blank (required) */ @NotBlank(message="Current time cannot be empty") @DateTimeStr(format ="yyyy-MM-dd HH:mm:ss", message = "Format error, correct format is: yyyy-MM-dd HH:mm:ss") private String currentTime; }
when the input fails to meet the conditions, an exception will be thrown, and then handled by the exception center. You can also use BindingResult, but after using this, you must manually handle exceptions, which invades the normal business logic. It is not recommended.
Common notes
here are Hibernate and javax Some common verification annotations under the validation package.
@Null
Restriction can only be null
@NotNull
Restriction must not be null
@AssertFalse
Restriction must be false
@AssertTrue
Restriction must be true
@DecimalMax(value)
The limit must be a number no greater than the specified value
@DecimalMin(value)
The limit must be a number not less than the specified value
@Digits(integer,fraction)
The limit must be one decimal, and the number of digits in the integer part cannot exceed integer, and the number of digits in the decimal part cannot exceed fraction
@Future
Limit must be a future date
@Max(value)
The limit must be a number no greater than the specified value
@Min(value)
The limit must be a number not less than the specified value
@Past
Limit must be a past date
@Pattern(value)
The restriction must conform to the specified regular expression
@Size(max,min)
The limit string length must be between min and max
@Past
Verify that the element value (date type) of the annotation is earlier than the current time
@NotEmpty
The element value of the validation annotation is not null and empty (string length is not 0, collection size is not 0)
@NotBlank
The element value of the validation annotation is not null (it is not null, and the length is 0 after removing the first space). Unlike @ NotEmpty, @ NotBlank is only applied to strings, and the spaces of strings will be removed during comparison
@Email
Verify that the element value of the annotation is email. You can also specify a custom email format through regular expression and flag
Nested entity validation and test cases
warm tip: entity class verification is only for the attributes of the first layer in the entity. If the verified entity class has another entity class B, you need to add @ valid annotation on the member variable of class B. If you add a member variable of class CurrentTimeDto type in Student class and verify its properties:
import lombok.Data; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.io.Serializable; @Data public class Student implements Serializable { private static final long serialVersionUID = 5285725868010678653L; @NotNull( message = "Name cannot be empty" ) @Length( message = "The maximum length of the name is {max}Characters" , min = 1 , max = 20 ) private String name; @NotNull( message = "Password cannot be empty" ) @Length( message = "Password must be at least{min}Characters, max {max}Characters" , min = 8 , max = 30 ) private String password; /** Age */ @NotNull(message = "Please enter age") @Range(message = "The age range is {min} reach {max} between", min = 1, max = 150) public Integer age; @NotNull(message = "Please enter address") @Size(max=32,message="address is null") private String address; @Pattern(regexp = "\\d{3}-\\d{8}|\\d{4}-\\d{7}|\\d{11}", message = "Incorrect mobile phone number") private String telephone; @Valid private CurrentTimeDto currentTimeDto; }
import lombok.Data; import javax.validation.constraints.NotBlank; import java.io.Serializable; @Data public class CurrentTimeDto implements Serializable { private static final long serialVersionUID = -7831097421296635187L; /** * Current time cannot be blank (required) */ //Set the time zone to the Shanghai time zone, and the time format is determined according to your needs. // @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8") @NotBlank(message="Current time cannot be empty") private String currentTime; }
the following are two test cases based on Student class. Add @ Valid annotation before the request parameter to start parameter verification:
/** * The parameter verification result is read from bindingResult * @param student * @param bindingResult * @return */ @ApiOperation(value = "bindingResult") @PostMapping("/bindingResult") public Object bindingResult(@RequestBody @Valid Student student, BindingResult bindingResult) { System.out.println("bindingResult---" + student); if (bindingResult.getErrorCount() > 0) { return bindingResult.getFieldError(); } return student; } /** * The parameter verification results can only be viewed from the log * @param student * @return */ @ApiOperation(value = "validParam") @PostMapping("/validParam") public Object validParam(@RequestBody @Valid Student student) { System.out.println("validParam---" + student); return student; }
Summary
I wish all migrant workers in the new era to constantly break themselves, improve themselves and reshape themselves, so as to make their career and life more brilliant.