【问题标题】:Understanding "globalValidator" in Spring MVC了解 Spring MVC 中的“globalValidator”
【发布时间】:2017-04-13 22:08:08
【问题描述】:

我有自定义验证器并在我的控制器中注册它

@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的描述:

另一种方法是在全局上调用 setValidator(Validator) WebBindingInitializer。这种方法允许您配置一个 所有带注释的控制器的验证器实例。这可以是 通过使用 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"/>

【问题讨论】:

  • 验证器名为globalValidator ...或者名为fooBar的验证器,如果你写&lt;mvc:annotation-driven validator="fooBar"/&gt;
  • 所以“globalValidator”只是之前创建的验证器的名称?那么,如果 Iwan 将其中两个放到全球范围内呢?
  • 你不能......你只能有一个全局验证器......

标签: java spring validation spring-mvc


【解决方案1】:

Validation section上的文档很清楚:

在 Spring MVC 中,您可以将其配置为 用作全局验证器 例如,在 @Valid 或 @Validated 控制器时使用 方法参数遇到和/或作为本地验证器 控制器通过@InitBinder 方法。全局和本地验证器 实例可以组合以提供复合验证

如果我在您的示例中正确理解了 FooValidator,您希望在每次验证时将其用作全局验证器,因此将其定义为 bean 并注入它,就像您在 mvc:annotation-driven XML 条目中直接显示的那样,正如您已经显示的那样。

在每个控制器之上,您可以通过 @InitBinder 注释进行自定义(仅在该控制器负责的表单上应用)。

作为旁注,在您的@RequestMapping 方法中接收 POST 请求,其中您的 @Valid 参数是:您可以在此之后有一个 BindingResult 条目来决定路线等。在您的示例中:

@RequestMapping("/foo", method=RequestMethod.POST)
public String processFoo(@Valid Foo foo, BindingResult result) {

   if(result.hasErrors()) {
      return "go/that/way";
   }
   //..
}

【讨论】:

    猜你喜欢
    • 2013-11-06
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多