SpringMVC supports data verification is the JSR303 standard, and it is verified by typing @NotNull, @Max, etc. on the bean's properties. JSR303 provides many annotation interfaces, and SpringMVC uses hibernate for these verifications, so we need to add a validator package for hibernate:
Relying on citations
compile 'javax.validation:validation-api:2.0.0.Final' compile 'org.hibernate:hibernate-validator:6.0.0.Final'
The framework has provided verification as follows:
Check annotations provided by JSR:
@Null The annotated element must be null
@NotNull The annotated element must not be null, cannot be null, can be ""
@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=) Verify whether the length of the object (Array,Collection,Map,String) is within the given 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(regex=,flag=) The annotated element must comply with the specified regular expression
Check annotations provided by Hibernate Validator:
@NotBlank(message =) can only be used on String, not null, and after calling trim(), the length must be greater than 0
@Email 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 commented string must be non-empty, cannot be null, "", can be " "
@Range(min=,max=,message=) The annotated element must be within the appropriate range
Example Demonstration
Create an entity class that needs to be verified:
package com.yiba.wifi.news.bean.model;import org.hibernate.validator.constraints.Length;import javax.validation.constraints.*;public class User { @NotBlank(message = "The user name cannot be null, the length must be greater than 0") String name; //User name @Min(value = 1, message = "Minimum age is 1 year old") @Max(value = 120, message = "Maximum age is 120") Integer age; //Age @Email(message = "Emailbox format error") @NotBlank(message = "Emailbox format error") String email; //Email @Length(min = 6, max = 12, message = "The password length must be between 6 and 12 digits") String pwd;//Password//get, set.........}Note that when verifying the email, when the email is "", or null, it will pass @Email verification, so email verification requires @Email and @NotBlank to work together.
controller interface design, add @Validated keyword where the parameter is accepted
/** * Login interface* @return */ @PostMapping("login") public String login(@Validated @RequestBody User user) { return "ok"; }Access tests:
When accessing data is in the following format
{ "name": "", "age": 0, "email": "", "pwd": ""}The response is:
{ "timestamp": 1524640724522, "status": 400, "error": "Bad Request", "exception": "org.springframework.web.bind.MethodArgumentNotValidException", "errors": [ { "codes": [ "NotBlank.user.email", "NotBlank.email", "NotBlank.java.lang.String", "NotBlank" ], "arguments": [ { "codes": [ "user.email", "email" ], "arguments": null, "defaultMessage": "email", "code": "email" } ], "defaultMessage": "email format error", "objectName": "user", "field": "email", "rejectedValue": "", "bindingFailure": false, "code": "NotBlank" }, { "codes": [ "NotBlank.user.name", "NotBlank.name", "NotBlank.java.lang.String", "NotBlank" ], "arguments": [ { "codes": [ "user.name", "name" ], "arguments": null, "defaultMessage": "name", "code": "name" } ], "defaultMessage": "User name cannot be null, the length must be greater than 0", "objectName": "user", "field": "name", "rejectedValue": "", "bindingFailure": false, "code": "NotBlank" }, { "codes": [ "Length.user.pwd", "Length.pwd", "Length.java.lang.String", "Length" ], "arguments": [ { "codes": [ "user.pwd", "pwd" ], "arguments": null, "defaultMessage": "pwd", "code": "pwd" }, 12, 6 ], "defaultMessage": "password length must be between 6 and 12 bits", "objectName": "user", "field": "pwd", "rejectedValue": "", "bindingFailure": false, "code": "Length" }, { "codes": [ "Min.user.age", "Min.age", "Min.java.lang.Integer", "Min" ], "arguments": [ { "codes": [ "user.age", "age" ], "arguments": null, "defaultMessage": "age", "code": "age" }, 1 ], "defaultMessage": "minimum age is 1 year old", "objectName": "user", "field": "age", "rejectedValue": 0, "bindingFailure": false, "code": "Min" } ], "message": "Validation failed for object='user'. Error count: 4", "path": "/yiba/sms/login"}You can see that the local request has failed to check the 4 fields. So is there a way for me to obtain exception information? The answer is yes, and we need to modify the controller interface.
/** * Login interface* * @return */ @PostMapping("login") public String login(@Validated @RequestBody User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { //There is a check that fails List<ObjectError> errorList = bindingResult.getAllErrors(); for (ObjectError error : errorList) { System.out.println(error.getDefaultMessage()); //Output specific error message} return "Parameter exception"; } return "ok"; }Request again, the request format is as follows
{ "name": "", "age": 0, "email": "", "pwd": ""}The response is as follows
Parameter exception
The information printed on the console is as follows:
The username cannot be null, the length must be greater than 0
Password length must be between 6 and 12 digits minimum age is 1 year old Email format error
You can see that we have obtained the verification information normally.
Let's do a reference correct access:
The request parameters are as follows:
{ "name": "zhaoyanjun", "age": 1, "email": "[email protected]", "pwd": "123456"}The response is as follows:
OK
The console outputs nothing.
Summarize
The above is an example demonstration of the Spring request parameter verification function introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!