我構建了一個Spring REST服務,並且我有一堆通過POST方法接收請求負載的端點。我在我的項目中包含了JSR 303規範,並且它對驗證工作正常。現在我如何讓我的應用程序發送一個JSON響應以及一個不同的狀態碼。目前該應用程序給出了一個400的錯誤頁面。當沒有滿足javax.validation.constraints。*時,發送休息響應而不是HTML頁面
更新:
我想通了,我需要包括BindingResult在我的方法,所以我可以從那裏提取的錯誤。
@PostMapping(value = "/validateBankInformation", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
protected ResponseEntity<BusinessSolutionVO> validateBankInformation(@Valid @RequestBody BankInformation bankInformation, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
List<ObjectError> errors = bindingResult.getAllErrors();
for (ObjectError error : errors) {
System.out.println(error.getDefaultMessage());
}
}
}
到目前爲止你做了什麼? – delephin