2012-08-25 29 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