Search code examples
javadata-bindingspring-mvcjstl

Spring form binding to Set inside c:forEach


I am using the Spring form tag library for form binding in my JSP. My command object contains a Set and I would like to iterate over that set using JSTL <c:forEach> and create a Spring <form:input> for each object in my set. I have seen how to do this with List:

<form:form>
  <c:forEach items="${itemList}" var="item" varStatus="status" >
    <form:input path="itemList[${status.index}].name" />
  </c:forEach>
</form:form>

My problem is that I am using an unordered Set and I don't believe that I can use the index property. What is the best practice for adding the contents of a Set to a Spring-bound form? I think I just need to convert to a List, but I am interested in any possible alternatives.


Solution

  • Your form-backing object should contain this data in a List, really. It doesn't make much sense to iterate over the set as the iteration order is not guaranteed to mean anything - and of course there is no concept of an index for a Set. I would imagine you probably have a certain desired order for these elements to appear on the page.