Introduce a,

The Spring Validation framework provides @Validated (Spring’s JSR-303 specification, which is a variant of the standard JSR-303) and javax provides @valid (the standard JSR-303 specification). With BindingResult, the parameter verification result can be provided directly. A specific validation annotation for a field, such as @notnull. There is not much difference between using @validated or @valid when checking whether the input parameters of the Controller conform to the specification. However, there are two differences in grouping, annotating places, nested validation and other functions:

1.Validated group: Provides the group function. Different authentication mechanisms can be used for different groups when verifying input parameters. Annotable location: Can be used for types, methods, and method parameters. However, it is not possible to use nested validation on member attributes: it is not possible to provide nested validation on method input parameters alone; Cannot be used on member attributes; There is no framework for nested validation; Can be used with nested validation annotation @valid for nested validation.

2.Valid group: no group function can annotate location: can be used on methods, constructors, method parameters, and member attributes (whether the two can be used on member attributes directly affects whether nested validation can be provided) Can be used on member properties to prompt the validation framework for nested validation; Can be used with nested validation annotation @valid for nested validation.

Second, the use of

1. Add dependencies after SpringBoot 2.3.0

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Copy the code

2. Configure Validation to return validation if the validation fails

@Configuration
public class WebConfig {
    @Bean
    public Validator validator(a) {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                //failFast indicates that the failFast is terminated immediately when the failFast fails and no further checks are performed.
                .failFast(true)
                .buildValidatorFactory();
 
        return validatorFactory.getValidator();
    }
 
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor(a) {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());
        returnmethodValidationPostProcessor; }}Copy the code

3. Write global exception capture, capture verification failure, unified return

@Slf4j
@ControllerAdvice
public class ValidatedExceptionHandler {

    @ResponseBody
    @ExceptionHandler(BindException.class)
    public String exceptionHandler2(BindException exception) {
        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {
            return result.getAllErrors().get(0).getDefaultMessage();
        }
        return "Parameter cannot be empty!";
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String exceptionHandler2(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {
            return result.getAllErrors().get(0).getDefaultMessage();
        }
        return "Parameter cannot be empty!"; }}Copy the code

4. Define the Dto and add annotation verification to the parameters

@Data
public class ValidDto {
    @NotEmpty(message = "Name must not be empty!")
    private String name;

    @NotBlank(message = "UserId cannot be empty!")
    private String userId;

    @Min(value = 1, message = "Wrong age!")
    @Max(value = 120, message = "Wrong age!")
    private int age;

    @NotBlank(message = "Mailbox must not be empty!")
    @Email(message = "Email error!")
    private String email;

    @NotBlank(message = "Mobile must not be empty!")
    @Pattern(regexp = "^ (13 14 [579] [0-9] | | 15 [0, 3, 5-9] 16 [6] | | 17 [0135678] [0-9] | | 18 19 [89]) \ \ d {8} $", message = "Wrong phone number!")
    private String mobile;

    @NotNull(message = "ValidVo cannot be empty!")
    @Valid
    private ValidVo validVo;

    @NotEmpty(message = "List1 cannot be empty!")
    @Size(min = 1, max = 2, message = "List1 data is too large")
    @Valid
    private List<ValidVo> list1;
}
Copy the code
@Data
public class ValidVo {
    @NotBlank(message = "gender is null")
    private String gender;
    @NotBlank(message = "test is null")
    private String test;
}
Copy the code

5. Controller

@RestController
@RequestMapping("/valid")
@CrossOrigin
public class ValidController {

    @GetMapping("/GetTest")
    public String getTest(@Valid ValidDto dto, BindingResult result) {
        if (result.hasErrors()) {
            return result.getAllErrors().get(0).getDefaultMessage();
        }
        return "success";
    }

    @GetMapping("/GetTest2")
    public String getTest2(@Validated ValidDto dto) {

        return "success";
    }

    @GetMapping("/GetTest3")
    public String getTest3(@Validated @RequestBody ValidDto dto) {

        return "success"; }}Copy the code