Search code examples
javascriptjavajspstruts2ognl

Struts 2 Form Bind Parameters To Collection Without Using Index


Struts Version: 2.3.16.3

Is there a way to populate a list of objects without having to specify the index? Currently I have to reference the collection like so:

<input name="myCollection[0].myProperty" value="some value" />

I really want to be able to do something like this:

<input name="myCollection[].myProperty" value="some value" />

I am dynamically adding and removing elements on the page with JavaScript and it has been a pain to get the indexing right with the JavaScript. Rather just have the backend add to the end of the collection in the order the elements come across from the form. Similar to how PHP processes it.

The docs for the parameters interceptor say that it is really just a ognl expression that the input name is binding to. I went to the ognl docs and it says you can reference array's like this:

array["length"]

which would be the next element in the array. The parameter interceptor is spitting out a message that it is rejecting this parameter name. I would really like to find a way to make this happen, even if it means extending the parameters interceptor.


Solution

  • You need somehow to identify which object some property belongs to. Indexes are simplest way to do that, so you cannot just remove them.

    There are many ways to achieve what you want. Look at Andrea's answer for one possible solution using javascript.

    You can also pull object properties to simple lists and later set them to object.

    E.g.

    private List<String> myProperty;
    

    can be referenced in JSP w/o indexes:

    <input name="myProperty" value="first value" />
    <input name="myProperty" value="second value" />
    

    Of course you if you have many properties you need to somehow sync them in JSP in such way that order and size of the properties in list is consistent for every property.