I am using Spring 3.0.2, Hibernate 3,5 (not sure) and JSP to create a web application. While creating a simple form (backed by pojo with simple attributes), everything works just fine. However now I am trying to create form like this:
- backing pojo is Person with let's say String 开发者_运维技巧name attribute
- Person has Set contacts attribute
- Contact pojo has String city and String phoneNumber attributes
I would like to be able to edit all the information on one page which means editing name, specifying city and phoneNumber.
Can any one of you direct me to the right path on how to bind nested collections? Should I create ModelAttribute("contactsForPerson") in the controller and pass it to the jsp and use this in my jsp?<form:form method="post" modelAttribute="person" >
<table>
<tr>
<td><form:hidden path="idPerson"/></td>
</tr>
<tr>
<td>Name</td>
<td><form:input path="name" value="${person.name}"/></td>
</tr>
<c:forEach items="${contactsForPerson}" var="a">
<tr>
<td>City</td>
<td><form:input path="contacts.city" value="${a.city}"/></td>
</tr>
<tr>
<td>Phone Number</td>
<td><form:input path="contacts.phoneNumber" value="${a.phoneNumber}"/></td>
</tr>
</c:forEach>
</table>
Question itself boils down to how to specity path attribute of Person so that set of Contacts is binded :)
Thanks in advance for your advice
Have a look at this similar stackoverflow question:
According to the answer the best way would be to set the collection as a list
<form:input path="contacts[0].phoneNumber"/>
or as a map:
<form:input path="contacts['contactId'].phoneNumber"/>
You can use a lazy list (Spring Autopopulating List, Apache Commons Lazy List, Guava lists) or a lazy map (Guava's Map Maker, Apache Commons lazy map) so you won't have to worry to create a new object when you need them in the list or map. Just when you do a get to a position which have not been initialized the list/map wll automatically create a new instance of the object.
精彩评论