Spring MVC data binding list example

In this tutorial, we will see how to perform data binding to a list; we are going to map fields in a page form to a list elements in a form backing object.

 

1. Technologies used

  • Spring 4.2.0.RELEASE
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.7
  • Tomcat 7.0

 

2. Project structure

SpringMVC-data-binding-list-example-5

 

3. Project dependencies

We need to add Spring 4 dependencies in our  Maven’ s pom.xml file

 

4. Model

In our form backing object, we’re going to add a new attribute of type List with the generic type of String, we call it shoppingList

File : Shopper.java

 

4. View

We’re going to add three fields to our form that represent items of a shopping list. We will store these items in the shoppingList of the Shopper class.

File : form.jsp

We have specified the path for data binding to the shoppingList by providing an index for each field in the form, so the first field points to the first element in the list, the second field points to the second element in the list, and the third field points to the third element in the list.

File : result.jsp

The result page will display the list of items submitted from the form page.

 

5. Controller

We’re going to add two methods addItems() and displayItems().

The first method will set a new instance of Shopper class in the model and then display our form.

The second method is invoked when we submit the form, in this method, we’re going to use the @ModelAttribute annotation to retrieve the shopper argument with the populated fields. After that, we place the shopper object into the model to display its content on the result page.

 

6. Configuration

We need to enable autodetection of our annotated controller by adding component scanning in the configuration file. We also need to declare the view resolver.

File : mvc-dispatcher-servlet.xml

 

7. Test It

Open the browser and type in: http://localhost:8080/SpringMVC-data-binding-list-example/shopper/form

Put some values into the form and click on the submit button.

SpringMVC-data-binding-list-example-4

Here we are with items of our shopping list :

SpringMVC-data-binding-list-example-2

 

Download source code