如何在Spring Boot应用程序中使用Hibernate Validation进行Bean验证? [英] How to do Bean Validation with Hibernate Validation in Spring Boot app?
问题描述
我正在Spring Boot应用程序中学习有关休眠验证的知识,并且我有一个Rest控制器和一个POST方法.当我发出请求时,如果未成功验证字段,则客户端应收到400错误请求,并且在正文中会显示类似验证失败"的消息.我尝试执行此操作,但消息未到.
I'm learning about Hibernate Validation in a Spring Boot app and I have a Rest controller and a POST method. And when I make a request, if a field isn't validated successfully, the client should receive 400 Bad Request and in the body a message like this "validation failed". And I try to do this, but the message didn't come.
这是身体:
{
"timestamp": "2020-06-06T07:56:11.377+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/ibantowallet"
}
在控制台日志中,我得到:
And in the console logs I get:
2020-06-06 10:56:11.371 WARN 7552 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity com.dgs.demotrans.api.TransactionController.sendMoneyIbanToWallet(com.dgs.demotrans.request.IbanToWalletRequest): [Field error in object 'ibanToWalletRequest' on field 'fromIban': rejected value [FR9151000 0000 0123 4567 89]; codes [Pattern.ibanToWalletRequest.fromIban,Pattern.fromIban,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [ibanToWalletRequest.fromIban,fromIban]; arguments []; default message [fromIban],[Ljavax.validation.constraints.Pattern$Flag;@3c555785,[a-zA-Z]{2}\d{2}[ ]\d{4}[ ]\d{4}[ ]\d{4}[ ]\d{4}[ ]\d{2}|DE\d{20}]; default message [IBAN validation failed]] ]
因此该消息为空,我希望客户端收到特定的消息"IBAN验证失败"或请提供金额",等等.我该怎么做?预先谢谢你!
So the message is empty, I want the client to receive the specific message "IBAN validation failed" or "Please provide an amount", etc. How can I do that? Thank you in advance!
推荐答案
您要么必须创建一个处理MethodArgumentNotValidException
的ControllerAdvice
方法,该方法就是休眠验证器抛出的错误,例如以下示例:
You would either have to create a ControllerAdvice
method that handles MethodArgumentNotValidException
, the error thrown by hibernate validator, like in this example:
@ResponseStatus(BAD_REQUEST)
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public CustomError methodArgumentNotValidException(MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
List<org.springframework.validation.FieldError> fieldErrors = result.getFieldErrors();
return mapToCustomError(fieldErrors);
}
或您可以在控制器方法中注入BindingResult
并检查其中的验证是否失败:
or you can inject BindingResult
in your controller method and check whether validation failed in there:
@PostMapping("/ibantoiban")
public ResponseEntity<String> sendMoneyIbanToIban(@Valid @RequestBody IbanToIbanRequest ibanToIbanRequest, BindingResult bindingResult) {
if (bindingResult.hasErrors()) { /** handle error here */ }
Transaction transaction = transactionService.sendMoneyIbanToIban(ibanToIbanRequest);
HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/ibantoiban" + transaction.getTransactionId().toString());
return new ResponseEntity(headers, HttpStatus.CREATED);
}
这篇关于如何在Spring Boot应用程序中使用Hibernate Validation进行Bean验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!