4

我正在构建一个用于输入足球比赛结果的 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

1 回答 1

4

Spring 可以绑定索引属性,因此您需要在命令上创建游戏信息对象列表,例如:

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 中,自动增长的集合现在是绑定列表的默认行为,但对于较低版本,您必须使用AutoPopulatingList而不仅仅是 ArrayList(仅作为参考:Spring MVC 和处理动态表单数据: AutoPopulatingList)。

于 2012-08-25T21:20:03.350 回答