在使用 spring-boot-starter-validation 时,需要在 controller 中使用 @Validated 注解来开启验证功能。@RequestBody@PathVariable 的验证方式有所不同:

  1. 对于 @RequestBody,需要在参数前加上 @Valid 注解,表示需要对该参数进行验证。例如:
@PostMapping("/user")
public User addUser(@Valid @RequestBody User user) {
    // ...
}
  1. 对于 @PathVariable,需要在方法上加上 @Validated 注解,并在 PathVariable 参数前加上 @NotBlank@NotNull 等验证注解。例如:
@GetMapping("/user/{id}")
public User getUserById(@Validated @NotBlank @PathVariable String id) {
    // ...
}

注意:如果想要自定义验证注解,需要在相应的注解类上加上 @Constraint 注解,并编写对应的验证器类。例如:

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = MyValidator.class)
public @interface MyAnnotation {
    String message() default "自定义验证注解失败";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

其中,MyValidator 为验证器类,需要实现 ConstraintValidator 接口。然后,在使用自定义注解时,就可以像使用其他注解一样使用了。例如:

@PostMapping("/user")
public User addUser(@Validated @RequestBody @MyAnnotation User user) {
    // ...
}
Spring Boot Starter Validation 使用指南:Controller 中的 @RequestBody 和 @PathVariable 验证

原文地址: https://www.cveoy.top/t/topic/mTsc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录