尝试在Spring Controller中使用BindingResult时获取ConstraintViolationException

问题描述 投票:0回答:2

我有和端点,我验证收到的包含对象集合的json文档。我想只记录这些没有通过验证的对象,当我想要存储在db中的其他对象时。在这种情况下,控制器应该返回200 OK。我试图为此目的使用BindingResult对象。不幸的是我总是得到一个ConstraintViolationException。它似乎在进入方法并抛出异常之前验证它。如何强制它使用BindingResult对象?

@RestController
@Validated
@RequestMapping(path = "/test")
class TestController {

    @PostMapping(consumes = APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> addObjects(@RequestBody @Valid List<Document> objects, BindingResult bindingResult) {

        if(bindingResult.hasErrors()){

        }            
        return new ResponseEntity<Void>(HttpStatus.OK);
    }

}

我正在使用Spring Boot 1.5.9.RELEASE和Java 8

java spring spring-boot bean-validation
2个回答
1
投票

我终于设法解决了这个问题。问题在于控制器类上的@Validated注释。使用此注释,spring会根据请求进行验证并抛出ConstraintViolationException。如果没有这个,稍后会触发验证,并且结果会按预期存储在BindingResult对象中


0
投票

你可以用它的注释添加模型类吗?请记住,如果Document类中有任何字段是您自定义的类,并且您希望它也经过验证,那么您还必须使用@Valid注释来装饰这些字段。

© www.soinside.com 2019 - 2024. All rights reserved.