Those who is very familiar with Struts must already know that if we put Collection as an attribute in the formbean and iterate the collection in the JSP with
indexed="true", something like this:
<logic:iterate id="friends" name="SomeForm" property="friends" indexed="true">
<html:text name="friends" property="name"/>
</logic:iterate>
then the output will be something like this, notice the name attribute of the input element:
<input type="text" name="friends[count].name">
Therefore, if you have ten friends, the count would be 0 to 9. But if DOM manipulation is required to delete or add friend, the
count might end up with incorrect sequence. For instance, user might remove 8 friends from the middle of the list, so only the values of
friends[0].name and
friends[9].name will be sent to the server. To be honest it was the first time I encountered this and it puzzled me for a few hours because the size of the friend's collection is still 10 with 8 NULL element in the list.
I didn't want to do null check for every element but yet I couldn't find any suitable Java Collection API to do the work for me. Finally I decided to make use of the
Jakarta Commons Collections, and the final code is something like this:
CollectionUtils.filter(friends, new Predicate() {
public boolean evaluate(Object o) {
return o != null;
}
});The API filters out the object from the collection based on the condition given by programmer.
All experts, I'm still not quite comfortable with the solution, it will be grateful if you can contribute some constructive ideas.