在使用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/bqmT 著作权归作者所有。请勿转载和采集!

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