我正在嘗試@RequestBody使用@Valid注釋對 Spring Boot JSON 物件執行驗證。
這個 JSON 物件 POJO 類將包含另一個嵌套物件。我為嵌套的物件類添加了欄位級注釋。
另外,我@Valid在主物件類中添加嵌套類物件時添加了注釋。
但是,當我們沒有傳遞正確的物件時,嵌套類物件的驗證仍然不會被觸發。
請找到以下代碼以供參考。
例外控制器類
@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;
}
學科類
@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 狀態。
任何幫助將不勝感激。
uj5u.com熱心網友回復:
嘗試添加@NotNull注釋Subject subject:
@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或空字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331712.html
