【问题标题】:Spring MVC 3 nested object validation is failing with @ValidSpring MVC 3嵌套对象验证因@Valid而失败
【发布时间】:2012-06-13 00:03:54
【问题描述】:

我有以下嵌套对象。我在我的控制器中使用@Valid 进行验证。这里 BindingResult 对象不验证子对象的名称字段。我错过了什么吗?

class Parent{
         @Valid  
         private Child child;
         //getter and setter for child object
 }

 class Child{
     @NotNull(messag="Name cannot be null")
     private String name;
     //getter and setter for name
 }

My controller validate method

@RequestMapping(value = "/validate", method = RequestMethod.POST)
public @ResponseBody  String validate(@Valid @ModelAttribute("parent") Parent parent, BindingResult bindingResult) {
    //Here I can see child name value if I say parent.getChild().getName()

  // But if  parent.getChild().getName() is null, bindingResult.hasErrors() is returning false

}

【问题讨论】:

    标签: spring spring-mvc bean-validation


    【解决方案1】:

    据我所知,@NotNull 不太适合字符串验证,因为 Spring 模型通常将“未收到对象”映射为“空白字符串”。

    请尝试@NotBlank 并查看 BindingResults 是否返回错误。

    【讨论】:

      【解决方案2】:

      你不能这样做。你不能像那样验证嵌套对象。

      您必须使用验证器。

      【讨论】:

        【解决方案3】:

        我之前也遇到过类似的问题。

        经过 2-3 天的研发,我成功验证了嵌套对象。我尝试对嵌套对象进行自定义验证。

        您需要创建一个自定义验证器类并在控制器和方法调用中自动装配它 validator.validate(parent, bindingResult) 它将返回与 bindingResult 对象中的嵌套对象字段绑定的错误,然后您可以像往常一样在jsp页面上显示。

        希望这对您有所帮助。干杯。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-08-18
          • 2014-05-18
          • 1970-01-01
          • 1970-01-01
          • 2011-03-21
          • 1970-01-01
          • 2021-10-02
          • 1970-01-01
          相关资源
          最近更新 更多