英文:
Can Spring automatically handle validation errors?
问题
我有一个带有 @Valid @RequestBody MyPojo pojo
参数的端点。当我调用端点并触发 javax.validation
失败时,请求会正确地返回状态码 400。然而,响应正文为空。
我可以在我的端点中添加一个 org.springframework.validation.Errors
参数,自行处理验证错误,并将它们返回给用户。但是,我是否可以让 Spring 在开箱即用的情况下自动完成这一操作?为什么我需要手动实现部分内置验证呢?
英文:
I have an endpoint with a @Valid @RequestBody MyPojo pojo
argument. When I call the endpoint and trigger a javax.validation
failure, the request properly returns with a status 400. However, the response body is empty.
I can add a org.springframework.validation.Errors
argument to my endpoint, handle the validation errors myself, and return them to the user. But can I get Spring to just do that out of the box? Why do I need to implement part of its built in validation manually?
答案1
得分: -1
你可以在你的JSR 380注解中使用消息输入,就像这样:
@NotNull(message = "姓名不能为空")
private String name;
更多信息:https://www.baeldung.com/javax-validation
英文:
You can use message input in your JSR 380 annotations like :
@NotNull(message = "Name cannot be null")
private String name;
专注分享java语言的经验与见解,让所有开发者获益!
评论