preface
In daily development, parameter verification is a very important link, strict parameter verification will reduce the probability of many bugs, increase the security of the interface. It also reduces unnecessary communication during docking. For example, when docking, the front end often throws a screenshot to say that there is a problem with the interface. You check for a long time and find that there is a problem with the parameters passed by the front end. For the above: today to share with you how to implement SpringBoot unified parameter verification.
implementation
Use the @validated annotation and parameter verification annotation, for example, @notempty, to verify parameters. It then captures the thrown exception ControllerAdvice and adjusts the output data.
TestController
@RestController
public class TestController {
/ * *
* Form request
* @paramForm request parameters
* @returnThe response data
* /
@PostMapping("/formRequest")
public ResultVo formRequest(@Validated RequestForm form){
return ResultVoUtil.success(form);
}
/ * *
* the JSON request
* @paramForm request parameters
* @returnThe response data
* /
@PostMapping("/jsonRequest")
public ResultVo jsonRequest(@RequestBody @Validated RequestForm form){
return ResultVoUtil.success(form);
}
}
Copy the code
RequestForm
@Data
public class RequestForm {
@NotEmpty(message = "Name cannot be empty.")
private String name;
@Min(value = 1 , message = "Must not be less than one year old.")
private Integer age;
@NotEmpty(message = "Gender cannot be empty.")
private Integer sex;
}
Copy the code
The test results
Request: http://localhost:8080/formRequest does not pass any parameters.
At this point SpringBoot has already verified the parameters against the validation annotations. And output a bunch of error messages. When the front end sees this error message during docking, the backhand is to give you a screenshot to tell you there is a problem with the interface. This is the time to use the ControllerAdvice specification for exception returns.
ControllerAdvice
@Slf4j
@RestControllerAdvice
public class ControllerAdvice {
/ * *
* Intercept form parameter validation
* /
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler({BindException.class})
public ResultVo bindException(BindException e) {
BindingResult bindingResult = e.getBindingResult();
return ResultVoUtil.error(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
}
/ * *
* Intercepting JSON parameter validation
* /
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResultVo bindException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
return ResultVoUtil.error(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
}
}
Copy the code
@RestControllerAdvice outputs the returned data as JSON. You can use @ControllerAdvice if you do not need it
The above code only returns an error message. It can be adjusted according to the actual situation.
At this point, the error message is more friendly, explicitly pointing out the missing parameters.
Common validation annotations
annotations | Runtime check |
---|---|
@AssertFalse | The annotated element must be false |
@AssertTrue | The annotated element must be true |
@DecimalMax(value) | The annotated element must be a number whose value must be less than or equal to the specified minimum |
@DecimalMin(Value) | The annotated element must be a number whose value must be greater than or equal to the specified minimum |
@Digits(integer=, fraction=) | The annotated element must be a number and its value must be within an acceptable range |
@Future | The annotated element must be a date to check if the given date is later than it is now |
@Max(value) | The annotated element must be a number whose value must be less than or equal to the specified minimum |
@Min(value) | The annotated element must be a number whose value must be greater than or equal to the specified minimum |
@NotNull | The annotated element must not be NULL |
@Null | The annotated element must be NULL |
@Past(java.util.Date/Calendar) | The date the annotated element must have passed, checking that the value in the annotation object represents a date earlier than the current one |
@Pattern(regex=, flag=) | The annotated element must conform to the regular expression to check whether the string can be matched by the regex-defined regular expression if specified by match |
@Size(min=, max=) | Annotated elements must be in the specified range (data types :String, Collection, Map and Arrays) |
@Valid | Recursively validates the associated object, if it is a collection or array, and if it is a map, it validates the value portion |
@CreditCardNumber | Perform a general verification of the credit card number |
The annotated element must be an E-mail address | |
@Length(min=, max=) | The annotated object must be a string and must be within the specified size |
@NotBlank | The annotated object must be a string and cannot be empty. Spaces will be ignored when checking |
@NotEmpty | The annotation object must be empty (data: String, Collection, Map, arrays) |
@Range(min=, max=) | Annotated elements must be in the appropriate range (data: BigDecimal, BigInteger, String, Byte, short, int, Long and wrapper classes of primitive type) |
@URL(protocol=, host=, port=, regexp=, flags=) | The annotated object must be a string to check if it is a valid URL. If protocol, host, etc., is provided, the URL must also meet the conditions provided |
case
@Data
public class ExampleForm {
@NotEmpty(message = "Name cannot be empty.")
@Length(min = 1 , max = 10 , message = "Name length 1 to 10")
private String name;
@Range(min = 1 , max = 99 , message = "Age range 1 to 99")
private Integer age;
@Pattern(regexp = "^ [1] [3,4,5,7,8] [0-9] {9} $" , message = "Wrong number")
private String phone;
@Email(message = "Wrong email format")
private String email;
@Valid
@Size(min = 1 ,max = 10 , message = "The number of elements in the list is 1 to 10")
private List<RequestForm> requestFormList;
@Future(message = "Start time must be greater than current time")
private Date beginTime;
}
Copy the code
Implement nested validation
In real development, the receptionist passes a list to the platform, and we not only limit the number of requests per list, but also verify the attribute values of the basic elements in the list. This is where nested validation comes in, and the way to do it is simple. This is done by adding @vaild to the list.
@Data
public class JsonRequestForm {
@Vaild
@Size(min = 1 ,max = 10 , message = "The number of elements in the list is 1 to 10")
private List<RequestForm> requestFormList;
}
Copy the code
The code address
https://gitee.com/huangxunhui/unifiedParamCheck.git
At the end
If you feel helpful to you, you can comment more, more like oh, you can also go to my home page to have a look, maybe there is an article you like, you can also click a concern oh, thank you.