Dynamic list item index with Spring Form
For decorated unordered lists like this:
private List<MyListItem> items = 开发者_Python百科LazyList.decorate(new ArrayList(),
FactoryUtils.instantiateFactory(MyListItem.class));
Is it compulsory to name the attributes in the form with an index number? such as:
<form:input path="items[1]" />
<form:input path="items[2]" />
Why can't I provide the two brackets like in PHP?
item[]
Because while dynamically creating the input list with DOM would be a problem to deal with item deletions...
The same way you ask why Spring does not support a generic kind of pattern such as item[], you could also be asking why your collection is not ordered according to the order of items shown by your form. Keep in mind: java.util.List is an ordered collection, so you must tell Spring where each item in the list must be inserted.
Workaround
1º option
Create an AutoPopulatingList as follows
private List<Item> items = new AutoPopulatingList(
new ElementFactory() {
public Object createElement(int index) throws ElementInstantiationException {
/**
* Any removed item will be handled as null.
* So we just remove any nullable item before adding to our List
* By using the following statement
*/
items.removeAll(Collections.singletonList(null));
return new Item();
}
});
2º option
Because Spring is open-source, you can create a custom BeanWrapperImpl. Behind the scenes, BeanWrapperImpl is responsible to populate your bean. Next, compile your custom Spring MVC
You could acces your variables like:
<form:input path="${item[0]}" />
<form:input path="${item[1]}" />
Another way is:
<c:forEach items="${items}" var="item">
<form:input path="${item}" />
</c:forEach>
精彩评论