【问题标题】:Populate List<String> in struts2 from form data从表单数据填充 struts2 中的 List<String>
【发布时间】:2011-04-29 16:53:10
【问题描述】:

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

我希望在 Struts2 中由表单数据填充字符串列表(或字符串数​​组,我真的不在乎)。

我已经看到了几个如何处理 indexed properties with beans 的示例,但是将单个字符串包装在对象中似乎相当愚蠢。

所以我有类似的东西

    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 从未被调用,但值被设置为空字符串。

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

【问题讨论】:

    标签: java list struts2 struts


    【解决方案1】:

    我相信你拥有它,你的 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>
    

    不确定上面的 value 属性是否正确,但我认为这样的事情会让你得到想要的结果。

    【讨论】:

    • 行得通,谢谢!您必须为看似简单的情况指定值,而不是为 bean 指定值,这似乎很奇怪。 耸耸肩 另外,当您说“字段引用的名称是“字符串 [x]”时,您需要的名称只是“字符串”,我假设您的意思是“字符串“……?最后,前者是 bean 的正确格式,对吧(例如 people[0].name 和 ArrayList people)?
    • 如果已解决问题,请将此答案标记为已解决。
    • @Quaternion:已经完成。尽管他(似乎不经意间)删掉了解决方案的关键部分;也就是说,该值应符合 %{getStrings().get(#stringStatus.index)}
    • @Chris:我不确定 value 字段必须那么复杂。您是否仅使用 value="[0]" 尝试过?当我最初发布答案时我忘记了它在迭代器循环中,这可能消除对复杂 %{getStrings().get(#stringStatus.index)} 的需要
    • 是的,表达式应该至少可以简化为 value="%{[#stringStatus.index]}",并且您应该能够删除 %{},因为在这种情况下应该假设 OGNL .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    相关资源
    最近更新 更多