2011-10-17 15 views
0

我有一個DTO(豆)與ArrayList領域:Spring MVC綁定:如何綁定ArrayList <...>?

public MyDTO { 
    ... 
    private List<MyThing> things; 
    ... 
    ... getters, setters and so on 
} 

在我initBinder我:

@InitBinder 
public void initBinder(WebDataBinder binder) { 
    ... 
    binder.registerCustomEditor(List.class, "things", new PropertyEditorSupport() { 
    @Override 
    public void setAsText(String text) throws IllegalArgumentException { 
     List<MyThing> things = new ArrayList<MyThings>; 

     // fill things array with data from text 
     ... 


     // On that stage things value is correct! 
     super.setValue(things); 
    } 
    }); 
} 

而且在我的控制器請求方法:

@RequestMapping({"save"}) 
public ModelAndView doSaveMyDTO(@ModelAttribute MyDTO myDTO) { 
    // very strange myDTO comes here=(
} 

的問題是,雖然我在registerCustomEditor工作人員things陣列是好的。

但是當我到達doSaveMyDTO方法 - MyDTO.things看起來像實際值的一個元素數組的數組:

預計(在initBinder的東西):

[value1, value2, value3] 

獲取doSaveMyDTO(myDTO.getThings ()):

[[value1], [value2], [value3]] 

爲什麼?請解釋...

回答

2

如果請求形成正確(things=v1&things=v2&things=v3things=v1,v2,v3),spring的內置轉換器應該將其正確轉換爲List - 無需註冊您自己的。

如果你的輸入是JSON,那麼你需要的@RequestBody代替@ModelAttribute

+0

不幸的是我有我的列表作爲JSON字符串。不管怎麼樣,謝謝你的建議 - 我會盡量做到在你的方式... – leshka

+0

啊,JSON是另一回事。你的json是怎樣的?對於它,我認爲你需要@RequestBody – Bozho