2012-01-27 57 views
0

我提交此數據通過Ajax(POST)添加Child實體:Spring MVC的:如何獲取BindingResult錯誤域的嵌套對象

(見這個問題對實體類定義的底部)

name = "Child Name" 
parent.id = 3 

一切都好。新的子實體已成功保存。

但如果不包括parent.id(僅name設置)

name = "Child Name" 

驗證結果返回該JSON(使用POST方法提交):

"errors":{"parent":"may not be null"} 

注意"parent"財產那個JSON。它應該返回parent.id而不是parent

由於客戶端腳本(HTML)上的字段名稱爲"parent.id"而不是"parent",所以會導致問題。

任何建議如何退貨parent.id而不是parent ??

下面是處理方法:

@RequestMapping(value = "/add", method = RequestMethod.POST) 
@ResponseBody 
public Map<String, ?> add(@Valid Child child, BindingResult result) { 

    Map<String, ?> out = new LinkedHashMap<String, ?>(); 

    if(result.hasErrors()){ 
     Map<String, String> errors = new LinkedHashMap<String, String>(); 
     for (FieldError error : result.getFieldErrors()) { 
      errors.put(error.getField(), error.getDefaultMessage()); 
     } 
     out.put("success", false); 
     out.put("errors", errors); 
     return out; 
    } else { 
     out.put("success", true); 
    } 

    return out; 

} 

這裏是實體類:

class Child { 
    private int id; 

    @NotNull 
    @Size(min = 5) 
    private String name; 

    @NotNull   
    private Parent parent; 

    //getter and setter methods 
} 

class Parent { 
    private int id; 

    @NotNull 
    private String name; 

    //getter and setter methods 
} 

謝謝。

回答

1

感謝@oehmiche的意見。

我結束了實體類改變這些:

class Child { 
    @NotNull 
    private int id; 

    @NotNull 
    @Size(min = 5) 
    private String name; 

    @NotNull 
    @Valid 
    private Parent parent = new Parent("Foo Foo"); 

    //getter and setter methods 
} 

class Parent { 
    @NotNull 
    private int id; 

    @NotNull 
    private String name; 

    public Parent(){ 
    } 

    public Parent(String name){ 
     setName(name); 
    } 

    //getter and setter methods 
} 

這是所提交的數據:

id = 1 
name = "Child Name" 
parent.id = 3 

注意id財產。我最終總是將其設置爲1,以繞過@NotNull約束。儘管id的值總是會被​​Hibernate取代(我使用自動生成策略)。

(我加@NotNull約束的家長id以及兒童類一致性)

然而,仍然有一個問題。我不得不總是設置父母的名字只是爲了繞過驗證約束的家長name屬性:

@NotNull 
@Valid 
private Parent parent = new Parent("Foo Foo"); 

這什麼建議嗎?

+0

在控制器中使用帶有「驗證組」的@Validated註釋http://beanvalidation.org/1.0/spec/#validationapi-validatorapi-groups – 2013-03-19 16:24:57

1

根據hiberante驗證規範對象圖驗證是使用屬性上的@Valid來驗證的(在您的情況下爲parent屬性)。但也有人提到null的值將被忽略(請參閱下面的註釋example)。 所以你的情況我建議實例在Child類空Parent對象和註釋是一個與@Valid

@Valid   
private Parent parent = new Parent(); 

也看到https://stackoverflow.com/a/5142960/160729

+0

謝謝@oehmiche。我認爲你的解決方案是正確的。但現在它驗證了null parent.name而不是null parent.id。任何進一步的建議? – 2012-01-29 21:13:15

相關問題