Populate List<String> in struts2 from form data

大憨熊 提交于 2019-12-22 06:25:13

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/5834944/populate-liststring-in-struts2-from-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!