The request parameters submitted by the front end need to be verified. If you use the IF else statement to verify, the verification is tedious. The @valid and @validated annotations solve this problem nicely.

Reference: www.oxingsoft.com/blog/articl…


Distinction between @Valid and @Validated

The @validated encapsulation is provided by Spring and is Valid.

Valid does not provide grouping.

@ No nested authentication is provided. Nested validation requires @VALID in front of the corresponding nested attribute.

The instance class adds validation annotations

@Data
public class Person {
	
	@NotEmpty(message = "Name cannot be empty.")
	private String name;
	
	@Max(value = 18, message = "No more than 18 years of age.")
	private String age;
	
	@Max(value = 1, message = "Gender can only be 0 and 1: 0= female 1= male.")
	@Min(value = 0, message = "Gender can only be 0 and 1: 0= female 1= male.")
	private Short sex;
	
}
Copy the code

The Controller method

@RestController
@Slf4j
public class VerifyController {

    @PostMapping(value = "/valid")
    public void verifyValid(@Valid @RequestBody Person person) {
        log.info("valid() method, the request params is: {}", JSON.toJSONString(person));
    }
    
    @PostMapping(value = "/validated")
    public void verifyValidated(@Validated @RequestBody Person person) {
        log.info("validated() method, the request params is: {}", JSON.toJSONString(person)); }}Copy the code

Define a global exception class to uniformly grab exceptions

@controlleradvice @responseBody public class GlobleExceptionHandler {/** * The Exception to be intercepted */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException.class) public Result<? > parameterExceptionHandler(MethodArgumentNotValidException e) { BindingResult exceptions = e.getBindingResult(); // Determine if there is an error message in the exception, if there is, use the message in the exception, otherwise use the default messageif (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if(! errors.isEmpty()) { FieldError fieldError = (FieldError) errors.get(0);return ResultGenerator.genErrorResult("1", fieldError.getDefaultMessage()); }}return ResultGenerator.genErrorResult("error"); }}Copy the code

Attached: Notes

@NULL limit can only be Null @Notnull Limit must not be Null @ASSERTFalse Limit must be false @AssertTrue Limit must be true @DecimalMax(Value) Limit must be a number not greater than the specified value @decimalmin (value) limit must be a number not less than the specified value @digits (integer,fraction) limit must be a decimal, and the number of Digits in the integer part must not exceed integer, The number of digits in the fractional part must not exceed the fraction@future limit must be a Future date. The @max (value) limit must be a number no greater than the specified value. The @min (value) limit must be a number no less than the specified value @pattern (value) limit must conform to the specified regular expression @size (Max,min) limit Character length must be between min and Max @past verifies that the element value (date type) of the annotation is earlier than the current time @notempty @notblank verifies that the element value of the annotation is not null and NotEmpty (string length is not 0, collection size is not 0), unlike @notempty, @notBlank applies only to strings and removes string whitespace for comparison. @email verifies that the element value of the annotation is Email. You can also specify a custom Email format using regular expressions and flag