Wednesday, September 18, 2013

How to get elements of list FROM JSP using JSTL and spring MVC 3

As we know we can populate the elements of list in JSP using JSTL tags. My requirement is to get the list of elements from JSP to controller.

I have one DTO class (ParentDTO) which internally contains the list of DTO (ChildDTO) and it looks like,
public class ParentDTO {

    private Long id;

    private List<ChildDTO> childs;

    //getters and setters here....

}

and ChildDTO looks like,

public class ChildDTO {

    private String name;

    private Long age;

    //getters and setters here....

}

In controller,
List<ChildDTO> childList = new ArrayList<ChildDTO>();
ChildDTO childOne = new ChildDTO();
childOne.setName("ABC");
childOne.setAge(10);

ChildDTO childTwo = new ChildDTO();
childTwo.setName("XYZ");
childTwo.setAge(5);

childList.add(childOne);
childList.add(childTwo);

model.addAttribute("childList", childList);

In JSP
<c:forEach var="child" items="${childList}">
    <tr>
        <td>Name :
          <input type="text" name="name" value="${child.name}"/>
        </td>
        <td>Age :
          <input type="text" name="age" value="${child.age}"/>
        </td>
    </tr>
</c:forEach>

Above code will populate the list properly. My requirement when user modify the details(name, age) and clicks on submit method.
When user clicks on submit I need to get the list of elements in the controller from the JSP and persist in DB.


SOLUTION:

Declare HTTPServletRequest in method argument and using request parameter get the column values as explained below,

String[] nameArr = request.getParameterValues("name");
String[] ageArr = request.getParameterValues("age");
List<ChildDTO> childList = new ArrayList<ChildDTO>();
if(nameArr != null && nameArr.length > 0 
        && ageArr != null && ageArr.length > 0
          && nameArr.length == ageArr.length) {
    for(int i = 0; i < nameArr.length; i++) {
        ChildDTO childOne = new ChildDTO();
        childOne.setName(nameArr[i]);
        childOne.setAge(Long.valueOf(ageArr[i]));
        childList.add(childOne);
    }
}

Once you convert it to DTO object then persist in DB.