我有自定义验证器,我在我的控制器中注册它
@Controller
public class MyController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new FooValidator());
}
@RequestMapping("/foo", method=RequestMethod.POST)
public void processFoo(@Valid Foo foo) { ... }
}
但是我也希望在其他控制器中注册,这样才能编写@Valid和Foo对象进行验证 . 从我看到的我明白,我可以使用@ControllerAdviced类来在每个控制器上注册验证器,或者使用
<mvc:annotation-driven validator="globalValidator"/>
但是如何注册我的验证器,Spring如何理解我想制作全局验证器?扫描每个实施 Validator 类?我可以用xml配置吗?如何使用这种方法?
我不明白Spring的描述:
另一种方法是在全局WebBindingInitializer上调用setValidator(Validator) . 此方法允许您跨所有带注释的控制器配置Validator实例 . 这可以通过使用SpringMVC名称空间来实现:xmlns =“http://www.springframework.org/schema/beans”xmlns:mvc =“http://www.springframework.org/schema/mvc”xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance”xsi:schemaLocation =“http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring -beans-3.0.xss http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd“>
<mvc:annotation-driven validator="globalValidator"/>
1 回答
文档在Validation section上非常清楚:
如果我在您的示例中正确理解了FooValidator,您希望在每次验证时将其用作全局Validator,因此将其定义为bean并将其注入直接显示在
mvc:annotation-driven
XML条目中,如您所示 .在每个控制器之上,您可以通过
@InitBinder
注释自定义(仅在控制器负责的表单上应用) .作为旁注,在接收POST请求的
@RequestMapping
方法中,@Valid
参数为:您可以在此之后立即拥有BindingResult
条目以对路由等做出决策 . 在您的示例中: