从表单数据填充struts2中的List

2024-03-06

我觉得这应该是非常明显的,但到目前为止我还没有找到答案。

我想要一个字符串列表(或一个字符串数组,我真的不在乎)由 Struts2 中的表单数据填充。

我看过几个关于如何做的例子bean 的索引属性 https://stackoverflow.com/questions/975883/populate-collection-from-struts2-form-submission,但是将单个字符串包装在对象内似乎相当愚蠢。

所以我有类似的东西

    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>

表单字段填充了它们的初始值(例如 1、2 等),但结果未正确回发。setStrings从未被调用,但值被设置为空字符串。

有人知道发生了什么事吗?提前致谢!


我相信,正如您所拥有的那样,您的 jsp 代码将呈现如下内容:

<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"/>
...

请注意,字段引用的名称是“strings[x]”,而您需要的名称只是“strings”。我会建议这样的事情:

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

不确定上面的值属性是否正确,但我认为这样的东西会给你想要的结果。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从表单数据填充struts2中的List 的相关文章

随机推荐