【问题标题】:Spring @RequestBody validation issue using @Valid annotation使用@Valid注释的Spring @RequestBody验证问题
【发布时间】:2021-12-09 01:47:46
【问题描述】:

我正在尝试使用 @Valid 注释对 Spring Boot @RequestBody JSON 对象执行验证。

这个 JSON 对象 POJO 类将包含另一个嵌套对象。 我为嵌套对象类添加了字段级注释。

另外,我在主对象类中添加嵌套类对象时添加了@Valid注解。

但是,当我们没有传递正确的对象时,嵌套类对象的验证不会被触发。

请在下面找到代码以供参考。

ExceptionController.class

@RestController
@RequestMapping("/student")
public class ExceptionController {
  
  @PostMapping
  @ResponseStatus(HttpStatus.CREATED)
  public String createStudent(@Valid @RequestBody Student student, HttpStatus status) {
    Student student1 = student;
    return "student data created!!";
  }
}

学生班

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
  @NotEmpty(message = "First Name field can not be null or empty")
  @NotBlank(message = "First Name field can not be blank")
  private String firstName;
  @NotEmpty(message = "Last Name field can not be null or empty")
  @NotBlank(message = "Last Name field can not be blank")
  private String lastName;
  @Valid
  private Subject subject;      
}

Subject.class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Subject {
  @NotEmpty(message = "Topic field can not be null or empty")
  @NotBlank(message = "Topic field can not be blank")
  private String topic;
}

当我没有在请求中为Subject 发送任何数据时,它不会给出任何异常并返回 HTTP 200 OK 状态。

我们将不胜感激。

【问题讨论】:

    标签: spring-boot validation


    【解决方案1】:

    尝试给Subject subject添加@NotNull注解:

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Student {
      @NotEmpty(message = "First Name field can not be null or empty")
      @NotBlank(message = "First Name field can not be blank")
      private String firstName;
      @NotEmpty(message = "Last Name field can not be null or empty")
      @NotBlank(message = "Last Name field can not be blank")
      private String lastName;
      @Valid
      @NotNull
      private Subject subject;      
    }
    

    只有当您实际发送 Subject 数据但带有空的 topic 属性时,您当前的验证才会起作用。

    在另一个主题上,您可能会删除@NotEmpty 注释,因为@NotBlank 不允许null 或空字符串。

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 2022-01-17
      • 1970-01-01
      • 2016-04-15
      • 2015-01-04
      • 1970-01-01
      • 2014-06-11
      • 2013-01-01
      相关资源
      最近更新 更多