October 05, 2009

Spring MVC - Dynamic list binding and validating the input data

It took quiet some time to figure out how to display a dynamic list of data on screen and get user input information back. We also had to perform validation on this dynamic list input data and display error message on the corresponding row.  
Here is the simple example to achieve the above requirement.

Consider that you need to display Parent and list of child information on a screen and get the Age and Sex information of each child. Also you need to show error message on the screen if the user has not entered the age or sex information.

1) Form bean

public class MotherFormBean{  
   private String name;  
   private List<Child> children;  
   public MotherFormBean() {  
     children= LazyList.decorate(new ArrayList(),  
 public class Child{  
   private String name;  
   private String age;  
   private String sex;  

Instead of initializing the List as normal ArrayList, use the LazyList class (Commons-collection package). This is to avoid "IndexOutOfBoundException" when the data is submitted back to the controller.

2) JSP

<form:form action="${formAction}" name="childrenDetails">  
   <c:foreach items="${command.children}" var="child" varStatus="loop">   
     <td><c:out value="${child.name}"></c:out>  
       <form:hidden path="children[${loop.index}].name"/>   
     <td><form:select path="children[${loop.index}].sex">  
        <option value="">--Please Select--</option>  
        <option value="M">Male</option>  
        <option value="F">Female</option>   
     <td><form:input path="children[${loop.index}].age"/></td>   

This code will print all the children names and show input fields for Age and Sex field.

3) Validator Class

When the List data is submitted back, Spring constructs the data back to the Form bean with help of the LazyList collection. Validation and raising error on these fields is very simple.

 public class MotherBeanValidator implements org.springframework.validation.Validator {  
   public void validate(Object target, Errors errors) {  
     MotherFormBean bean = (MotherFormBean) target;  
     List<Child> children = bean.getChildren();  
     for (int i = 0; i < children.size(); i++) {  
       if (StringUtils.isEmpty(children.get(i).getSex()))   
        errors.rejectValue("children[" + i + "].sex", "select.sex");  
       if (StringUtils.isEmpty(children.get(i).getAge()))   
        errors.rejectValue("children[" + i + "].age", "select.age");  

JSP Changes:
Include <form:errors> tag after the sex and age input fields.
 <form:errors path="children[${loop.index}].sex"/>   
Hope this helps you in displaying the Collection data using Spring MVC and validating it.

Thanks to Matt Flemings blog for shedding some light on the LazyList.


  1. Hi.
    This is for showing the dynamic list of child items. can you please help me writing a function that adds the item into the list using spring binding ?


  2. Hi,

    I have the same issue. I need to add elements to the list dynamically using javascript. How can I bind these elements. Currently I am getting IndexOutOfbound exception when I add the elements.

    Please help.

  3. Hi,

    As mentioned in this post, use LazyList.decorate() method to initialize your list in the Model. This will avoid throwing IndexOutOfBoundException.


  4. Used LazyList. It works great with Adding new objects.

    It is not recognizing if the objects are REMOVED from the list.

    Is there any work around? or am I missing anything?

  5. sorry, I am not clear with my above question. My UI should be able to ADD and DELETE items.

    LazyList is working great with ADD. It is binding dynamically. But when I DELETE, it is not removing from the LazyList.

    What can I do to remove the items from list?

  6. LazyList will only initialize the objects in the list with the "index" you provide from your UI.

    Consider you had 3 elements in the list and you deleted 2nd element (index=1) on your UI. When you submit the form, size of the LazyList will still be 3 but the second element in the List will be NULL.
    So you can handle the delete operation in the code by doing a NULL check.

    1. This is really HelpFul..I got stucked with how to validate a list!!
      But your post helped me on that..
      Thanks a lot!!

  7. I want to add text boxes that depend upon the click on the type of radio button. In spring how can I achieve this? I tried with java script and added successfully but the problem is then How will I bind my data so that I can see validation and submit the data to backend? Please help. Thanks -Ankit

    1. http://outbottle.com/spring-3-mvc-adding-objects-to-a-list-element-on-the-fly-at-form-submit-generic-method/

  8. http://outbottle.com/spring-3-mvc-adding-objects-to-a-list-element-on-the-fly-at-form-submit-generic-method/

    refer the above site

  9. Thanks mate, this worked a treat!!!

  10. Thanks friend !! [${loop.index}] really worked ....

  11. Lazy List is showing error!

  12. Having little experience in working with forms of collecting and processing information in our company, I was glad that the management offered to use. This greatly simplified my work, I stopped worrying about mistakes and now I don't forget about something important part of the work thanks, mobile form builder software. I'm sure here https://form.com/form-software/mobile-forms/ many will find this software application.

  13. A IEEE project is an interrelated arrangement of exercises, having a positive beginning and end point and bringing about an interesting result in Engineering Colleges for a particular asset assignment working under a triple limitation - time, cost and execution. Final Year Project Domains for CSE In Engineering Colleges, final year IEEE Project Management requires the utilization of abilities and information to arrange, plan, plan, direct, control, screen, and assess a final year project for cse. The utilization of Project Management to accomplish authoritative objectives has expanded quickly and many engineering colleges have reacted with final year IEEE projects Project Centers in Chennai for CSE to help students in learning these remarkable abilities.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai