【发布时间】: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 状态。
我们将不胜感激。
【问题讨论】: