I use Spring MVC 3.0 and JSP. I have an object:
public class ObjectWrapper {
private List<SomeTO> someTOs;
}
Class SomeTO
contains fields like name
and id
. How can I create a form on which an user can dynam开发者_运维百科ically add to list of SomeTO
? I googled it and found something about spring:bind
, but it's unclear for me.
In the form backing method, set the list to a LazyList which is part of the apache commons collection library.
Factory notificationFactory = new Factory() {
public Object create() {
SomeTO rtVl = new SomeTO();
return rtVl;
}
};
myFormBacking.setSomeTOs(LazyList.decorate(myFormBacking.getSomeTOs));
Then on your form, when you send the data to the server you can do it like this
<input name="someTOs[0].name" value="" />
And if your using
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
then you can simply go.
<form:input path="someTOs[0].name" />
Before posting the data to the server, to make pruning easier, set the number of elements in the collection. So if the user added 5 TOs, then send that length value in the form post.
ON the server now, you must prune the list before you save it. Here is the function for pruning
public List<SomeTOs> pruneList(List<SomeTOs> unpruned,int expectedLength){
List<SomeTOs> rtVl = new ArrayList<SomeTOs>();
for (int i = 0; i < unpruned.length && expectedLength; ++i){
rtVl.add(unpruned.get(i);
}
return rtVl;
}
Here is the use of the prune function in the on submit (before save)
wrapper.setSomeTOs(pruneList(wrapper.getSomeTOs(),Integer.parseInt(request.getParameter("expectedLength)));
精彩评论