将JSR-303验证错误转换为Spring的BindingResult

问题描述:

我在Spring控制器中有以下代码:

I have the following code in Spring controller:

@Autowired
private javax.validation.Validator validator;

@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submitForm(CustomForm form) {
    Set<ConstraintViolation<CustomForm>> errors = validator.validate(vustomForm);
    ...
}

是否可以将errors映射到Spring的BindingResult对象,而无需手动检查所有错误并将它们添加到BindingResult?像这样:

Is it possible to map errors to Spring's BindingResult object without manually going through all the errors and adding them to the BindingResult? Something like this:

// NOTE: this is imaginary code
BindingResult bindingResult = BindingResult.fromConstraintViolations(errors);

现在我可以用@Valid注释CustomForm参数,并让Spring注入BindingResult作为另一种方法的参数,但是在我看来,这不是一个选择.

I now it is possible to annotate CustomForm parameter with @Valid and let Spring inject BindingResult as another method's parameter, but it's not an option in my case.

// I know this is possible, but doesn't work for me
public String submitForm(@Valid CustomForm form, BindingResult bindingResult) {
    ...
}

一种更简单的方法可能是使用Spring的抽象org.springframework.validation.Validator,您可以通过在上下文中包含以下bean来获得验证器:

A simpler approach could be to use Spring's abstraction org.springframework.validation.Validator instead, you can get hold of a validator by having this bean in the context:

<bean id="jsr303Validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

@Autowired @Qualifier("jsr303Validator") Validator validator;

有了这种抽象后,您可以通过传递绑定结果的这种方式使用验证器:

With this abstraction in place, you can use the validator this way, passing in your bindingResult:

validator.validate(obj, bindingResult);