我有自定義的簡單端點,它回傳一些物件(在我的例子中是記錄)。我想驗證回傳的輸出資料的正確性(例如,輸出 DTO 確實將所有欄位都設定為非空值)。
執行此類驗證的最佳位置在哪里?是否可以更正驗證器中的回傳值(例如,將欄位“上次訪問資源”的值 null 更改為“尚未訪問資源”)
示例說明性代碼:
public record SomeDTO(String nameOfUser, String lastAccessedInfo, List<SomeDTO> recursiveIsFun) {
}
@GetMapping(value = "/somethingEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
public SomeDTO getSomething(HttpServletRequest request) throws IOException, InterruptedException {
final String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
.replacePath(null)
.build()
.toUriString();
return new SomeDTO("user accessed at " baseUrl, null, Collections.emptyList());
}
uj5u.com熱心網友回復:
如果它在為空時應該具有默認值,那么我寧愿在物件本身中執行它,例如:
@GetMapping(value = "/somethingEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
public SomeDTO getSomething(HttpServletRequest request) throws IOException, InterruptedException {
final String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
.replacePath(null)
.build()
.toUriString();
return new SomeDTO("user accessed at " baseUrl, null, Collections.emptyList())
.handleNullValues();
}
public record SomeDTO(String nameOfUser, String lastAccessedInfo, List<SomeDTO> recursiveIsFun) {
public SomeDTO handleNullValues(){
if(lastAccessedInfo == null){
lastAccessedInfo = "default value";
}
return this;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/471294.html
上一篇:如何在布局中禁用它后,在magento的結帳頁面中單擊下訂單上的名字欄位的必填欄位驗證
下一篇:PHP驗證。它不會進入顯示頁面
