java 从表单数据填充 struts2 中的 List<String>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5834944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populate List<String> in struts2 from form data
提问by Chris
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.
我想要一个字符串列表(或一个字符串数组,我真的不在乎)由 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.
我已经看到了几个关于如何使用 beans进行索引属性的示例,但是将单个字符串包装在一个对象中似乎相当愚蠢。
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.
表单字段填充了它们的初始值(例如 1、2 等),但结果没有正确回传。setStrings
永远不会被调用,但值被设置为空字符串。
Anybody have any idea what's going on? Thanks in advance!
有人知道发生了什么吗?提前致谢!
回答by nmc
I believe as you have it, your jsp code would render something like:
我相信当你拥有它时,你的 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"/>
...
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:
请注意,字段引用的名称是“strings[x]”,因为您需要名称仅为“strings”。我会建议这样的:
<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.
不确定上面的 value 属性是否正确,但我认为这样的事情会得到你想要的结果。