Most of the verification of http request data in the b/s system is done on the client side, which is also for simplicity and user experience considerations, but server-side verification is indispensable in some systems with high security requirements.
Spring3 supports the JSR-303 verification framework. JSR-303 is a sub-spec in Java EE 6 called BeanValidation. The official reference implementation is hibernate Validator (has nothing to do with Hibernate ORM). JSR 303 is used to verify the values of fields in Java Beans.
Validator mainly checks the rationality of the data submitted by the user, such as whether it is empty, whether the password length is greater than 6 digits, whether it is purely digital, etc. So how can you use such a powerful verification framework in spring boot?
Combined with validation and springboot
1. Add tags to bean
Part of the code:
The tag needs to be added to the attribute, @NotBlank The meaning of the tag is explained at the end of the article
public class User { private Integer id; @NotBlank(message = "{user.name.notBlank}") private String name; private String username;2. Turn on verification in Controller
Add the @Validated tag to the request parameter in Controller to enable verification
@RequestMapping(method = RequestMethod.POST) public User create(@RequestBody @Validated User user) { return userService.create(user); }3. Create a new error message configuration file under resource
Create a new prompt message 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 the classpath.
The ValidationMessages.properties file is encoded as ASCII. The data type is key value. key "user.name.notBlank" is the corresponding message value in the braces of the first step bean.
value is a prompt message, but it is ASCII. (The content is "The name cannot be empty")
4. Customize the exception handler to catch error messages
When the verification fails, an exception will be thrown. The exception message is the prompt information configured in ValidationMessages.properties. The exception handler is defined here. Capture exception information (because there may be multiple items that fail to pass the verification, they are captured and processed uniformly) and throw it to the front end. (This is the front and back end separate sender)
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. Attach some tag meanings
| limit | illustrate |
|---|---|
| @Null | Limit only to 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 that is 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 a decimal, and the number of digits in the integer part cannot exceed integer, and the number of digits in the fraction part cannot exceed fraction |
| @Future | The limit must be a future date |
| @Max(value) | The limit must be a number that is no greater than the specified value. |
| @Min(value) | The limit must be a number not less than the specified value |
| @Past | The limit must be a past date |
| @Pattern(value) | The restriction must comply with the specified regular expression |
| @Size(max,min) | Limit character 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 | Verify that the element value of the verification annotation is not null and not empty (the string length is not 0, the collection size is not 0) |
| @NotBlank | Verify that the element value of the annotation is not empty (not null, the length is 0 after removing the first space). Unlike @NotEmpty, @NotBlank is only applied to strings and will remove the string spaces when comparing. |
| Verify that the element value of the annotation is Email, and you can also specify a custom email format through regular expressions and flags. |
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, on the page, there are two element name input boxes, password input library, and submit button.
After submitting to the background, use Validator for verification, and then forward to demo.html if there is an error,
We first write an entity class to receive user input and use Validator annotation to verify:
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 empty") private String name; @NotEmpty(message="password cannot be empty") @Length(min=6,message="password length cannot be less than 6 digits") 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 to everyone's learning and I hope everyone will support Wulin.com more.