Article directory
1. Specifications and common annotations of abnormal verification
In web development, for request parameters, it is generally necessary to verify the validity of the parameters. The original way of writing is to judge each field one by one. This method is too uncommon, so Java's JSR 303: Bean Validation specification is to solve this problem.
JSR 303 is just a specification, and there is no specific implementation. Currently, only hibernate-validator is usually used for unified parameter verification.
The verification type defined by JSR303 (refer to "3.4. Configuration file injection value data verification")
Constraint | details |
---|---|
@Null | The annotated element must be null |
@NotNull | The annotated element must not be null |
@AssertTrue | The annotated element must be true |
@AssertFalse | Annotated elements must be false |
@Min(value) | The annotated element must be a number whose value must be greater than or equal to the specified minimum value |
@Max(value) | The annotated element must be a number whose value must be less than or equal to the specified maximum value |
@DecimalMin(value) | The annotated element must be a number whose value must be greater than or equal to the specified minimum value |
@DecimalMax(value) | The annotated element must be a number whose 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 in the acceptable range |
@Past | The annotated element must be a date in the past |
@Future | The annotated element must be a future date |
@Pattern(value) | The annotated element must match the specified regular expression |
Hibernate Validator additional constraints | |
Constraint | details |
-------------- | -------------- |
The annotated element must be an email address | |
@Length | The size of the annotated string must be within the specified range |
@NotEmpty | The annotated string must be non-empty |
@Range | The annotated element must be in the appropriate scope |
Usage: Add the above annotation to the attribute field of ArticleVO, and then add the @Valid annotation to the parameter verification method, such as:
[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-ZFBNFoas-1644632559630) (images/screenshot_1597453255173.png)]
[External link image transfer failed, the source site may have For the anti-leech mechanism, it is recommended to save the image and upload it directly (img-tfNVD8J1-1644632559631)(images/screenshot_1597453285578.png)]
When the user input parameter does not conform to the validation rules given in the annotation, a BindException or MethodArgumentNotValidException will be thrown.
2. Assert assertion and IllegalArgumentException
When I told you about general exception handling before, the user input exception judgment is handled in this way. This method can also be used, but we have learned so much knowledge that we can optimize it.
//服务层,模拟用户输入数据导致的校验异常
public void userBizError(int input) {
if(input < 0){
//模拟业务校验失败逻辑
throw new CustomException(
CustomExceptionType.USER_INPUT_ERROR,
"您输入的数据不符合业务逻辑,请确认后重新输入!");
}
//…… 其他的业务
}
A better way to write it is as follows. Use org.springframework.util.Assert to assert that input >= 0. If the condition is not met, an IllegalArgumentException is thrown, and the parameter is invalid.
//服务层,模拟用户输入数据导致的校验异常
public void userBizError(int input) {
Assert.isTrue(input >= 0,"您输入的数据不符合业务逻辑,请确认后重新输入!");
//…… 其他的业务
}
The org.springframework.util.Assert assertion provides a large number of assertion methods to verify data validity for various data types, and it is more convenient for us to write code using it.
3. Friendly data verification exception handling (global handling of user input exceptions)
We know that when data validation fails, an exception BindException or MethodArgumentNotValidException will be thrown. Therefore, we deal with these two exceptions globally to prevent programmers from repeating coding and causing trouble.
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public AjaxResponse handleBindException(MethodArgumentNotValidException ex) {
FieldError fieldError = ex.getBindingResult().getFieldError();
return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR,
fieldError.getDefaultMessage()));
}
@ExceptionHandler(BindException.class)
@ResponseBody
public AjaxResponse handleBindException(BindException ex) {
FieldError fieldError = ex.getBindingResult().getFieldError();
return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR,
fieldError.getDefaultMessage()));
}
We are known to use the org.springframework.util.Assert assertion to throw an IllegalArgumentException if the condition is not met. The following global exception handler can be used
@ExceptionHandler(IllegalArgumentException.class)
@ResponseBody
public AjaxResponse handleIllegalArgumentException(IllegalArgumentException e) {
return AjaxResponse.error(
new CustomException(CustomExceptionType.USER_INPUT_ERROR,
e.getMessage())
);
}