我在 Spring/JPA 中有一個簡單的問題。據說,我有這種格式的請求:
模型/BillDto.java
public class BillDto {
private String desc;
private Long id;
private Integer amount;
public BillDto(String desc, long id, int amount) {
this.desc = desc;
this.id = id;
this.amount = amount;
}
}
或作為這種 json 格式
{
"desc": "String",
"id": 0,
"amount": 0
}
這是控制器
控制器/BillController.java
@RequestMapping(method = RequestMethod.POST)
public void create(@RequestBody BillDto billDto) {
billService.create(billDto); // some service to execute
}
但是,當我不小心以錯誤的格式請求時,生成的 SQL 將不會執行,因此它回傳 500 代碼。例如,
{
"desc": "String",
"id": 0
}
如何在最短的代碼行中處理此錯誤?在將它傳遞給服務之前,如何驗證 json 請求以匹配模型/dto?
uj5u.com熱心網友回復:
您可以對使用@Valid@RequestBody 注釋的 BillDto 引數使用注釋。這將告訴 Spring 在進行實際方法呼叫之前處理驗證。如果驗證失敗,Spring 將拋出一個MethodArgument NotValidException默認情況下將回傳 400 (Bad Request) 回應。
@RequestMapping(method = RequestMethod.POST)
public void create(@Valid @RequestBody BillDto billDto) {
billService.create(billDto); // some service to execute
}
在 POST 或 PUT 請求中,當我們傳遞 JSON 有效負載時,Spring 會自動將其轉換為 Java 物件,現在它可以驗證結果物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/408186.html
標籤:
