Springboot uses the validation framework validation example,
In the B/s system, most http request data is verified on the client. This is also for the sake of simplicity and user experience. However, in some systems with high security requirements, server verification is indispensable.
Spring3 supports the JSR-303 verification framework, JSR-303 is a sub-specification in Java EE 6, called BeanValidation, the official reference implementation is hibernate Validator (has no relationship with Hibernate ORM ), JSR 303 is used to verify the value of fields in Java Bean.
Validator mainly checks the rationality of the data submitted by the user, such as whether the password is empty, whether the password length is greater than 6 digits, and whether it is a pure number. So how can we use such a powerful verification framework in spring boot.
Combination of validation and springboot
1. Add tags to bean
Some code:
The tag must be added to the attribute. @ NotBlank the tag meaning is explained at the end of this article.
public class User { private Integer id; @NotBlank(message = "{user.name.notBlank}") private String name; private String username;
2. enable verification in Controller
Add @ Validated label to request parameters in Controller to enable verification
@RequestMapping(method = RequestMethod.POST) public User create(@RequestBody @Validated User user) { return userService.create(user); }
3. Create an error message configuration file under resource
Create the prompt information configuration file "ValidationMessages. properties" in the resource Directory.
Note: The name must be "ValidationMessages. properties" because SpringBoot automatically reads the error message in ValidationMessages. properties in classpath.
The ValidationMessages. properties file is encoded as ASCII. The data type is key value. Key "user. name. notBlank" indicates the value of message in the label braces of the bean in the first step.
Value indicates the prompt information, but it is ASCII. (The content is "name cannot be blank")
4. custom exception processor to capture error messages
If the verification fails, an exception is thrown. The error message is the prompt information configured in ValidationMessages. properties. The exception processor is defined here. Capture the exception information (because the verification fails, multiple items may be captured and processed in a unified manner) and then deliver it to the front-end. (This is the development of frontend and backend separation)
public void MethodArgumentNotValidException(Exception ex, HttpServletRequest request, HttpServletResponse response) { logger.error( ":" + CommonUtil.getHttpClientInfo(request), ex); MethodArgumentNotValidException c = (MethodArgumentNotValidException) ex; List<ObjectError> errors =c.getBindingResult().getAllErrors(); StringBuffer errorMsg=new StringBuffer(); errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";")); pouplateExceptionResponse(response, HttpStatus.INTERNAL_SERVER_ERROR, errorMsg.toString()); } private void pouplateExceptionResponse(HttpServletResponse response, HttpStatus errorCode, String errorMessage) { try { response.sendError(errorCode.value(), errorMessage); } catch (IOException e) { logger.error("failed to populate response error", e); } }
5. attached some label meanings
Restrictions |
Description |
@ Null |
The limit can only be null. |
@ NotNull |
The limit must not be null. |
@ AssertFalse |
The limit must be false. |
@ AssertTrue |
The limit must be true. |
@ DecimalMax (value) |
The limit must be a number not greater than the specified value. |
@ DecimalMin (value) |
The limit must be a number no less than the specified value. |
@ Digits (integer, fraction) |
The limit must be a decimal number. The number of digits in the integer part cannot exceed integer, and the number of digits in the decimal part cannot exceed fraction. |
@ Future |
The limit must be a future date. |
@ Max (value) |
The limit must be a number not greater than the specified value. |
@ Min (value) |
The limit must be a number no less than the specified value. |
@ Past |
The limit must be a previous date. |
@ Pattern (value) |
The limit must comply with the specified regular expression. |
@ Size (max, min) |
The character length must be between min and max. |
@ Past |
The element value (date type) of the verification annotation is earlier than the current time |
@ NotEmpty |
The element value of the verification annotation is not null and not empty (the string length is not 0, and the set size is not 0) |
@ NotBlank |
The element value of the verification annotation is not empty (not null, the length is 0 after the first space is removed), different from @ NotEmpty, @ NotBlank: only applies to strings and removes spaces of strings during comparison. |
@ Email |
Verify that the annotation element value is Email. You can also use a regular expression and flag to specify a custom email format. |
Example
@Pattern(regexp="^[a-zA-Z0-9]+$",message="{account.username.space}") @Size(min=3,max=20,message="{account.username.size}")
Example 2
Here we mainly use annotations for learning. Let's talk about our needs first:
We have a demo.html. There are two element name input boxes on the page, the password input library, and the submit button.
After delivery to the background, use validatorfor verification. Then, if an error occurs, it is forwarded to demo.html,
We first write an entity class to receive user input, and use the Validator annotation for verification:
Package com. kfit. demo; import org. hibernate. validator. constraints. length; import org. hibernate. validator. constraints. notEmpty; public class Demo {private long id; @ NotEmpty (message = "name cannot be blank") private String name; @ NotEmpty (message = "password cannot be blank ") @ Length (min = 6, message = "password Length cannot be less than 6 characters") private String password; publiclong getId () {return id;} publicvoid setId (longid) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password ;}@ Override public String toString () {return "Demo [id =" + id + ", name =" + name + ", password = "+ password +"] ";}}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.