2010-12-12 100 views
0

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

@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> 

当过程已经提交,支柱总是给我4对象,而不是内部集合中的2个对象。我知道使用索引属性中的其他解决方法将解决问题,但对于我的情况,我需要收集是动态的。有办法解决这类问题吗?

我已经试过别人的注释以及:

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

但这些都不曾

+0

仅供参考:您无需在您的操作中初始化helloBeans。你的二传手会做到这一点。 – 2010-12-12 16:45:45

回答

0

据我所知,你必须使用:

<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”和“value”属性):

<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 ...并使用字符串连接为“name”属性构建正确的OGNL。

注意如果您的动态行为是在JSP服务器端就

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

在S内使用时,会得到当前迭代的索引:iterator标签。