Spring MVC map multiple dynamic form elements with the same name

javascript, jsp, spring, spring-mvc

Solution

I was able to get it working by following the example from: http://lifeinide.blogspot.com/2010/12/dynamic-forms-lazylist-and-transparent.html?showComment=1355160197390#c6923871316812590644

I did make one adjustment, however. For the form names, I used:

<input name="locationList[0].locationName" />

instead of what the article suggests:

<input name="myFormObject.elements[0].property" />

Problem

I have a Spring MVC application and I am wondering how to successfully map multiple, dynamic form elements with the same name in my JSP page to my object class. For example: In my locations.jsp page, I have multiple dropdown boxes: ``` <form id="tabs-3-form"> <input id="locations-1" name="location" /> <input id="locations-2" name="location" /> <input id="locations-3" name="location" /> ... (more can be added or deleted dynamically by user) </form> ``` I'm using jQuery to POST the form to my controller: ``` $("#tabs-3-form").submit(function() { $.ajax({ type: 'POST', url: '/searchResults', data: $(this).serialize(), dataType: 'json', success: function(data) { ... } }); return false; }); ``` My LocationsController.java is set up as follows: ``` @RequestMapping(value = "/locationResults", method = RequestMethod.POST) public @ResponseBody LocationsCollection locationsCollection ( @ModelAttribute(value = "location") Location location, BindingResult result ) { LocationsCollection locationsCollection = new LocationsCollection(); locationsCollection.addLocation(location); // Anything else to do here? return locationsCollection; } ``` `LocationsCollection.java` just contains a List of `Location` objects. Do I need to add brackets to the names of my input fields? Will MVC automatically do the mapping to a List, as it does with the other form elements? If anyone could provide an example, I'd appreciate it.

Original source