@RequestBody 不限于 POJO 类型并且 BindingResult hasErrors 始终为 false [英] @RequestBody not restricting to POJO type and BindingResult hasErrors always false
问题描述
我在开发的早期没有遇到这个问题,只是在调试另一个问题时注意到发生了这种情况.这发生在所有 REST 端点上,但下面是一个示例:
I was not experiencing this problem early in development but just noticed that this was happening when debugging another problem. This happens on all REST endpoints, but below is an example:
@RestController
@RequestMapping("/editlisting")
public class EditParkingSpaceListingController {
@Autowired
ParkingSpaceRepository parkingSpaceRepository;
@Autowired
ParkingSpaceListingRepository parkingSpaceListingRepository;
@RequestMapping(method = RequestMethod.PUT)
public ResponseEntity<String> editParking(@RequestBody ParkingSpaceListingClient pslc, BindingResult result) {
if (result.hasErrors()) {
return new ResponseEntity<String>("", HttpStatus.BAD_REQUEST);
}
// Code to save pslc data to database.
现在,如果我发送一个带有正文的 HTTP 请求
Now, if I send an HTTP request with the body as
{ }
我收到 200 响应,当我检查 MongoDB 时,集合中有一个新的空文档.如果我发送一个没有括号的空正文,它会按预期返回 400.如果我发送一个包含 POJO 中不存在的随机垃圾数据的正文,BindingResult 似乎没有发现错误并且一个新的空白文档仍然存在创建.
I get a 200 response and when I check MongoDB, there is a new empty document in the collection. If I send an empty body with no brackets, as expected it will return 400. If I send a body with random garbage data that does not exist in the POJO, BindingResult does not seem to pick up the error and a new blank document is still created.
推荐答案
您需要按照以下步骤进行输入文档验证:
You need to follow the below steps for the input document validations:
(1) 将 javax.validation
包约束(如 @NotNull
、@Size
等)添加到您的 ParkingSpaceListingClient
bean 类.
(1) Add the javax.validation
package constraints (like @NotNull
, @Size
, etc..) to your ParkingSpaceListingClient
bean class.
(2) 将@Validated annotation
添加到您的控制器方法中,将验证错误捕获到BindingResult
对象中.
(2) Add @Validated annotation
to your controller method, to capture the validation errors into BindingResult
object.
您可以查看这里 有关输入验证的更多详细信息.
You can look here for more details on Input Validations.
这篇关于@RequestBody 不限于 POJO 类型并且 BindingResult hasErrors 始终为 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!