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.
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for uploading files.
What Is Spring MVC? Spring MVC is a library within the Spring framework that simplifies handling HTTP requests and responses. It's built on the Servlet API and is an essential component of the Spring Framework.
tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc.
Spring MVC Framework works as follows: All the incoming requests are intercepted by the DispatcherServlet that works as the front controller. The DispatcherServlet then gets an entry of handler mapping from the XML file and forwards the request to the controller.
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With