我正在使用Spring 3和JSR 303.我有一个表单支持对象,其嵌套对象需要进行验证。在下面的示例中,如何验证formObject.getFoo()。getBean()?当我运行下面的代码时,结果参数始终为空,即使HTML页面没有提交任何内容,验证失败时也是如此。请注意,当我通过调用validate(formObject.getFoo().getBean(), Bean.class)
手动验证它时,它可以工作(即验证失败)。
@Controller
public class FormController {
@RequestMapping(method = RequestMethod.POST)
public void process(HttpServletRequest request, @Valid FormObject formObject, BindingResult result) {
...
}
// This is the class that needs to be validated.
public class Bean {
@NotBlank
private String name;
}
public class Foo {
private Bean bean;
}
public class FormObject {
private Foo foo;
}
}
答案 0 :(得分:12)
如果要将验证级联到子对象中,则必须将@Valid注释放在父对象的字段中:
public class Bean {
@NotBlank
private String name;
}
public class Foo {
@Valid
private Bean bean;
}
public class FormObject {
@Valid
private Foo foo;
}