【问题标题】:Getting ConstraintViolationException when trying to use BindingResult in Spring Controller尝试在 Spring Controller 中使用 BindingResult 时出现 ConstraintViolationException
【发布时间】:2019-02-20 10:58:52
【问题描述】:

我有一个端点,在那里我验证收到的包含对象集合的 json 文档。当我想将其他对象存储在数据库中时,我只想记录这些未通过验证的对象。在这种情况下,控制器应该返回 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);
    }

}

我正在使用带有 Java 8 的 Spring Boot 1.5.9.RELEASE

【问题讨论】:

    标签: java spring spring-boot bean-validation


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2016-05-14
        • 1970-01-01
        • 2011-12-03
        • 1970-01-01
        • 1970-01-01
        • 2021-09-17
        • 2016-06-02
        • 1970-01-01
        • 2011-12-07
        相关资源
        最近更新 更多