Struts2 中支援使用List在頁面和Action之間直接傳遞表格資料。下面是一個示例:
public class Person {
int id;
String name;
int age;
float height;
}
這是一個POJO,getter和setting省略了。
action中可以這樣使用:
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