【问题标题】:struts 2 collection type conversion problemstruts 2 集合类型转换问题
【发布时间】:2010-12-12 03:59:57
【问题描述】:

我在 struts 2 中使用类型转换来转换 bean 的集合时遇到了麻烦。 我有以下动作类:

@Validation()
@Conversion()
public class HelloWorldAction extends ActionSupport {


    private List<HelloBean> helloBeans = new ArrayList<HelloBean>();


    public String execute() throws Exception {
        System.out.println(helloBeans);
        return SUCCESS;
    }
    public List<HelloBean> getHelloBeans() {
        return helloBeans;
    }

     @TypeConversion(rule = ConversionRule.COLLECTION, converter = "foo.HelloBean")
    public void setHelloBeans(List<HelloBean> helloBeans) {
        this.helloBeans = helloBeans;
    }

}

还有我的 bean 类:

public class HelloBean {
    private String name;
    private Integer age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

}   

还有我的 JSP 文件:

<s:form action="helloWorld">

    <s:textfield name="helloBeans.name" label="name1"/>
    <s:textfield name="helloBeans.name" label="name2" />
    <s:textfield name="helloBeans.age" label="age1"/>
    <s:textfield name="helloBeans.age" label="age2"/>
        <s:submit />
    </s:form>

提交过程后,struts 总是给我 4 个对象,而不是集合内的 2 个对象。我知道在属性中使用索引的其他解决方法可以解决问题,但就我而言,我需要动态收集。有没有办法解决这种问题?

我也尝试过其他注释:

@Element(value =foo.HelloBean.class )
    @CreateIfNull( value = true )
    @KeyProperty( value = "name" )
    private List<HelloBean> helloBeans = new ArrayList<HelloBean>();

但这些都不起作用

【问题讨论】:

  • 仅供参考:您不需要在操作中初始化 helloBeans。你的二传手会这样做。

标签: types struts2 type-conversion


【解决方案1】:

您必须使用 AFAIK:

    <s:form action="hello-world">
        <s:textfield name="helloBeans[1].name" label="name1"/>
        <s:textfield name="helloBeans[1].age" label="age1"/>
        <s:textfield name="helloBeans[2].name" label="name2" />
        <s:textfield name="helloBeans[2].age" label="age2"/>
        <s:submit />
    </s:form>

我认为最大的问题不是必须以这种方式完成,而是您认为这意味着它不能是动态的,考虑到文本字段呈现得更少(实际上更少,因为我删除了 'id'和“价值”属性):

<input type="text" name="helloBeans[1].name"/>
<input type="text" name="helloBeans[1].age"/>
... 

没有理由你不能像测试视图那样在你的jsp中动态处理这个:

    <h1>Display HelloBeans</h1>
    <table>
        <s:iterator value="helloBeans">
            <tr>
                <td><s:property value="name"/></td>
                <td><s:property value="age"/></td>
            </tr>
        </s:iterator>
    </table>

或者,如果您的问题是客户端问题,则使用 JavaScript(或更好的 JS 库,例如 jQuery)向 DOM 添加新文本字段...并使用字符串连接为“名称”属性构建正确的 OGNL。

请注意,如果您的动态行为是 JSP 中的服务器端,那么

<s:property value="#helloBeans.index" /> 

当在 s:iterator 标签内使用时,将获得当前迭代的索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    相关资源
    最近更新 更多