将 JSR-303 验证错误转换为 Spring 的绑定结果
2022-09-02 13:41:49
我在Spring控制器中有以下代码:
@Autowired
private javax.validation.Validator validator;
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submitForm(CustomForm form) {
Set<ConstraintViolation<CustomForm>> errors = validator.validate(form);
...
}
是否可以映射到Spring的对象,而无需手动检查所有错误并将它们添加到?像这样:errors
BindingResult
BindingResult
// NOTE: this is imaginary code
BindingResult bindingResult = BindingResult.fromConstraintViolations(errors);
我知道可以用参数注释参数,并让Spring注入作为另一个方法的参数,但在我的情况下,这不是一个选项。CustomForm
@Valid
BindingResult
// I know this is possible, but doesn't work for me
public String submitForm(@Valid CustomForm form, BindingResult bindingResult) {
...
}