Struts2中支持使用List在頁面和Action之間直接傳遞表格數據。下面是一個示例:
public class Person {
int id;
String name;
int age;
float height;
}
public class MyAction {
public List getPeopleList() { … }
public void setPeopleList( List peopleList ) { … }
…
}
在我們使用Person類之前,需要添加一個配置文件,MyAction-conversion.properties,把這個文件和MyAction放在一起。
這個文件里只有一行內容:
Element_peopleList=Person
前綴Element_是一個常量,表明等號左邊的表達式中跟在這個常量后面的是Action類中一個List類型的字段名。
等號右邊的表達式是全類名(包含package)
下面是一個頁面的代碼片段:
<s:form action="update" method="post" >
<s:iterator value="peopleList" status="stat">
<s:hidden
name="peopleList[%{#stat.index}].id"
value="%{peopleList[#stat.index].id}"/>
<s:textfield label="Name"
name="peopleList[%{#stat.index}].name"
value="%{peopleList[#stat.index].name}"/>
<s:textfield label="Age"
name="peopleList[%{#stat.index}].age"
value="%{peopleList[#stat.index].age}" />
<s:textfield label="Height"
name="peopleList[%{#stat.index}].height"
value="%{peopleList[#stat.index].height}"/>
<br/>
</s:iterator>
<s:submit value="Update"/>
</s:form>
使用這段代碼,Struts2會創建一個Person類的ArrayList,并且用setPersonList這個方法把頁面表格中的值傳遞回Action。
如果你是想從用戶界面中動態創建列表值,需要允許Struts2給列表中類的實例。那么在配置文件MyAction-conversion.properties中添加一行:
CreateIfNull_peopleList = true






這是一個POJO,getter和setting省略了。
action中可以這樣使用:





這個文件里只有一行內容:
Element_peopleList=Person
前綴Element_是一個常量,表明等號左邊的表達式中跟在這個常量后面的是Action類中一個List類型的字段名。
等號右邊的表達式是全類名(包含package)
下面是一個頁面的代碼片段:


















使用這段代碼,Struts2會創建一個Person類的ArrayList,并且用setPersonList這個方法把頁面表格中的值傳遞回Action。
如果你是想從用戶界面中動態創建列表值,需要允許Struts2給列表中類的實例。那么在配置文件MyAction-conversion.properties中添加一行:
CreateIfNull_peopleList = true