How to bind a dynamic list of fields in a JSP

2019-03-31 06:47发布

问题:

I am building a JSP page for entering football game results. I get a list of unsettled games and I want to list them like this:

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]

I never know how many games will be listed. I am trying to figure out how to set up the binding so that the controller can access these fields after the form is submitted.

Can someone please guide me in the right direction. I am using Spring MVC 3.1

回答1:

Spring can bind indexed properties, so you need to create a list of game info objects on your command, like:

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
}

In your controller:

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

In your JSP you will have to set the paths for the inputs like:

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 
....

If I'm not mistaken, in Spring 3 the auto-growing collections is now the default behavior for binding lists, but for lower versions you had to use an AutoPopulatingList instead of just an ArrayList (just as a reference: Spring MVC and handling dynamic form data: The AutoPopulatingList).