gpt4 book ai didi

java - Struts2 填充列表

转载 作者:行者123 更新时间:2023-12-01 05:24:32 25 4
gpt4 key购买 nike

我在填充 Struts2 中的用户定义对象属性列表时遇到问题。

这是我的示例(省略 getters/setters):

public class Foo { private String attr1; private String attr2; }

public class Bar { private List foos; }

public class StrutsAction extends ActionSupport { private Bar bar; }

我在 JSP 中的代码如下(摘录):

<tr><td><input type="text" name="bar.foos.attr1"/></td><td><input type="text" name="bar.foos.attr2"</td></tr>
<tr><td><input type="text" name="bar.foos.attr1"/></td><td><input type="text" name="bar.foos.attr2"</td></tr>

我需要每个表行在列表中使用每个属性创建 1 个 foo 项目,但是我的代码在传递时为每个属性创建一个新的 foo 对象,最终得到 4 个 foo 而不是 2 个!

我知道我可以通过将索引硬编码到 html 中来解决问题,如下所示:

<tr><td><input type="text" name="bar.foos[0].attr1"/></td><td><input type="text" name="bar.foos[0].attr2"</td></tr>
<tr><td><input type="text" name="bar.foos[1].attr1"/></td><td><input type="text" name="bar.foos[1].attr2"</td></tr>

我想知道是否可以在不对索引进行硬编码的情况下完成?

最佳答案

你说你的行数是可变的。让我们将其命名为 numOfRows...尝试像这样重写您的示例:

<table>
<s:iterator status="stat" value="(numOfRows).{ #this }" >
<tr>
<td><input type="text" name="bar.foos[%{#stat.index}].attr1"/></td>
<td><input type="text" name="bar.foos[%{#stat.index}].attr2"/></td>
</tr>
</s:iterator>
</table>

您可以找到有关迭代器标签 there 的文档...查看页面底部。

<小时/>

如果你在渲染阶段没有 numOfRows ,那么恐怕生成文本字段的唯一方法是客户端的 javascript ....

[编辑]

关于索引...如果您有这样的索引,则不必担心:

<table>
<tr>
<td><input type="text" name="bar.foos[0].attr1"/></td>
<td><input type="text" name="bar.foos[0].attr2"/></td>
</tr>
<tr>
<td><input type="text" name="bar.foos[3].attr1"/></td>
<td><input type="text" name="bar.foos[3].attr2"/></td>
</tr>
<tr>
<td><input type="text" name="bar.foos[5].attr1"/></td>
<td><input type="text" name="bar.foos[5].attr2"/></td>
</tr>
</table>

Struts 会正确地进行转换...您只需要注意,缺少索引的对象将为 null...因此您应该在操作中将它们过滤掉。

关于java - Struts2 填充列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9872659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com