1

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 dynamically add to list of SomeTO? I googled it and found something about spring:bind, but it's unclear for me.

1 Answer 1

2

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)));
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain me, what with form code? I don't understand what with command.someTOs[0].someProperty = "YES"; Sorry for crazy questions)
Hhehe, sorry... after I posted the answer I saw the properties name and Id. Let me fix it up for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.