Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate List<String> in struts2 from form data

I feel this should be exceedingly obvious, but so far I've failed to find an answer.

I want to have a list of strings (or an array of strings, I really don't care) get populated by form data in Struts2.

I've seen several examples of how to do indexed properties with beans, but wrapping a single string inside an object seems fairly silly.

So I have something like

    public class Controller extends ActionSupport {

        private List<String> strings = new ArrayList<String>();
        public Controller() {
            strings.add("1");
            strings.add("2");
            strings.add("3");
            strings.add("4");
            strings.add("5");
        }
        public String execute() throws Exception {
            return ActionSupport.SUCCESS;
        }
        public List<String> getStrings() {
            return strings;
        }

        public void setStrings(List<String> s) {
            strings = s;
        }
    }    

...

<s:iterator value="strings" status="stringStatus">
   <s:textfield name="strings[%{#stringStatus.index}]" style="width: 5em" />
</s:iterator>

The form fields get populated with their initial values (e.g. 1, 2, etc), but the results are not properly posted back. setStrings is never called, but the values get set to empty strings.

Anybody have any idea what's going on? Thanks in advance!

like image 440
Chris Avatar asked Apr 29 '11 16:04

Chris


1 Answers

I believe as you have it, your jsp code would render something like:

<input type="text" name="strings[0]" style="width: 5em" value="1"/>
<input type="text" name="strings[1]" style="width: 5em" value="2"/>
<input type="text" name="strings[2]" style="width: 5em" value="3"/>
...

Notice that the name of the field references are "strings[x]" where as you need the name to be just "strings". I would suggest something like:

<s:iterator value="strings" status="stringStatus">
   <s:textfield name="strings" value="%{[0].toString()}" style="width: 5em" />
</s:iterator>

Not sure if the value attribute above may is correct, but I think something like this will get you the desired result.

like image 56
nmc Avatar answered Oct 23 '22 10:10

nmc