Spring Validation framework uses

Posted by izua on Mon, 03 Jan 2022 04:07:49 +0100

1, Introduction

The Spring Validation framework provides @ Validated (Spring's JSR-303 specification, a variant of the standard JSR-303) for the parameter validation mechanism, and javax provides @ Valid (standard JSR-303 specification), which can directly provide parameter validation results in combination with BindingResult. The specific validation annotation for the field, such as @ NotNull.
When checking whether the input parameters of the Controller comply with the specification, there is no much difference in the basic verification function between @ Validated or @ Valid. However, the two functions are different in grouping, annotation place, nested verification and so on:

  1. @Validated
    Grouping: it provides grouping function. Different authentication mechanisms can be adopted according to different groups during parameter entry verification.
    Annotative location: can be used on types, methods, and method parameters. However, it cannot be used on member properties
    Nested validation: it is used on method input parameters and cannot provide nested validation function alone; Cannot be used on member properties; It is also unable to provide a framework for nested verification; It can perform nested verification with the nested verification annotation @ Valid.
  2. @Valid
    Grouping: no grouping function
    Annotative location: it can be used on methods, constructors, method parameters and member properties (whether they can be used on member properties directly affects whether nested verification can be provided)
    Nested validation: it is used on method input parameters and cannot provide nested validation function alone; It can be used on member attributes to prompt the verification framework for nested verification; It can perform nested verification with the nested verification annotation @ Valid.

2, Use

1. Add dependency after springboot 2.3.0

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

2. Configure validation to return if verification fails

@Configuration
public class WebConfig {
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                //failFast means that as long as the verification fails, the verification will be ended immediately without subsequent verification.
                .failFast(true)
                .buildValidatorFactory();
 
        return validatorFactory.getValidator();
    }
 
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());
        return methodValidationPostProcessor;
    }
}

4. Write a global exception capture. If the capture verification fails, it will be returned uniformly

@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!";
    }
}

5. Define Dto and add annotation verification on the parameters

@Data
public class ValidDto {
    @NotEmpty(message = "name Cannot 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 cannot be empty!")
    @Email(message = "Wrong mailbox!")
    private String email;

    @NotBlank(message = "mobile Cannot be empty!")
    @Pattern(regexp = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$", message = "Wrong mobile 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 The data is too large")
    @Valid
    private List<ValidVo> list1;
}
@Data
public class ValidVo {
    @NotBlank(message = "gender is null")
    private String gender;
    @NotBlank(message = "test is null")
    private String test;
}

6. 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";
    }
}

Topics: Spring Boot