2012-08-25 27 views
4

我正在構建一個用於輸入足球比賽結果的JSP頁面。我得到的懸而未決的遊戲列表,我想一一列舉如下:如何綁定JSP中字段的動態列表

team1 vs team4 
    [hidden field: game id] 
    [input field for home goals] 
    [input field for away goals] 

team2 vs team5 
    [hidden field: game id] 
    [input field for home goals] 
    [input field for away goals] 

我從來不知道有多少場比賽將陸續上市。我想弄清楚如何設置綁定,以便控件可以在提交表單後訪問這些字段。

有人可以請指導我在正確的方向。我使用Spring MVC 3.1

回答

4

Spring可以bind indexed properties,所以你需要創建遊戲的列表信息的對象對你的命令,如:

public class Command { 
    private List<Game> games = new ArrayList<Game>(); 
    // setter, getter 
} 

public class Game { 
    private int id; 
    private int awayGoals; 
    private int homeGoals; 
    // setters, getters 
} 

在你的控制器:

@RequestMapping(value = "/test", method = RequestMethod.POST) 
public String test(@ModelAttribute Command cmd) { 
    // cmd.getGames() .... 
    return "..."; 
} 

在您的JSP將不得不爲輸入設置路徑,如:

games[0].id 
games[0].awayGoals 
games[0].homeGoals 

games[1].id 
games[1].awayGoals 
games[1].homeGoals 

games[2].id 
games[2].awayGoals 
games[2].homeGoals 
.... 

如果我是沒錯,在Spring 3中,auto-growing collections現在是綁定列表的默認行爲,但對於較低版本,您必須使用AutoPopulatingList而不是ArrayList(僅作爲參考:Spring MVC and handling dynamic form data: The AutoPopulatingList)。

+0

有趣的是,假如它沒有Spring的AutoPopulatingList,Apache commons集合的LazyList和其他類似的東西, –

+0

謝謝。只要我回到我的電腦上,我就會試試這個。 –

+0

@Jerome Dalbert:我提到了那些使用較低Spring版本的人使用AutoPopulatingList,以便他們知道「陷阱」。 Spring 3.0.0中對binder的更改。 – Bogdan