user1884155 user1884155 - 4 years ago 98
Java Question

Struts2 sending list data from JSP to Action class: alternative way

I was explaining to a colleague the way of getting list data from a JSP page to back to the action class by using indices as explained here and here. He didn't quite understand and fumbled a bit on his own until he suddenly he made it work by not using indices at all!

In his JSP page he had:

<input type="checkbox" name="contactNameList" value="someValue1">
<input type="checkbox" name="contactNameList" value="someValue2">
<input type="checkbox" name="contactNameList" value="someValue3">
<input type="checkbox" name="contactNameList" value="someValue4">

In his action class he had the 'appropiate' setters:

public List<String> getContactNameList()

public void setContactNameList(List<String> list)

I'm baffled as to why this work. I think this works because he is sending non-bean data (in this case strings) and there is an intelligence build into Struts2/OGNL to append values to lists rather than overwrite them.

Can anybody explain with great detail what is going behind the hood in this "no indices" case? How is the list of strings instantiated and populated with the snippets above?

Answer Source

You should understand that bean data and not bean data are passed as parameters to the action. The parameters has a structure that you can find if you implement ParameterAware.

Note that all parameter values for a given name will be returned, so the type of the objects in the map is java.lang.String[].

Then XWork Type Conversion make its best to convert this map to beans properties. See Built in Type Conversion Support.

Routine type conversion in the framework is transparent. Generally, all you need to do is ensure that HTML inputs have names that can be used in OGNL expressions. (HTML inputs are form elements and other GET/POST parameters.)

In the no indexes case parameters are mapped under the one key, rather than indexed names are used under their own names.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download