2012-06-13 63 views
4

我有以下嵌套對象。我在我的控制器中使用@Valid進行驗證。這裏BindingResult對象不驗證Child對象的名稱字段。我錯過了什麼?Spring MVC 3嵌套對象驗證失敗@Valid

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 

} 

回答

2

據我所知,@NotNull不太適合字符串驗證,因爲Spring模型經常會將「沒有收到對象」映射到「空白字符串」。

請嘗試@NotBlank並查看BindingResults是否返回錯誤。

-1

我以前也有類似的問題。

做了2-3天后R & D我成功地驗證了嵌套對象。我試圖對嵌套對象進行自定義驗證。

您需要創建一個自定義驗證器類,並在控制器和方法調用validator.validate(parent,bindingResult)中自動裝入它,它會返回綁定結果對象中嵌套對象字段的綁定錯誤,然後您可以像往常一樣在jsp頁面上顯示它。

希望這可以幫助你。乾杯。

0

你不能這樣做。你不能像這樣驗證嵌套對象。

你必須使用驗證器。