struts2中有許多很好的特性,比如在設置好getter和setter方法后,加上前端的匹配設置,后台即可自動將前端輸入的數據轉換為后台的相應的對象。
如現在傳入一個Person類的對象,其中Person類中有name和age等屬性。

1 class Person { 2 private String name; 3 private int age; 4 5 public void setName(String name) { 6 this.name = name; 7 } 8 9 public String getName() { 10 return name; 11 } 12 13 public void setAge(int age) { 14 this.age = age; 15 } 16 17 public int getAge() { 18 return age; 19 } 20 }
則前端對應的表單寫法如下

1 <form action="addperson" method="post"> 2 <input type="text" name="person.name"> 3 <input type="number" min="0" max="200" name="person.age"> 4 <button type="submit"></button> 5 </form>
這個時候前端提交action至struts.xml,根據action匹配對象的Java類實現功能。

1 <action name="addperson" class="com.wsy.action.PersonAction" method="addPerson"> 2 <result>/WEB-INF/content/success.jsp</result> 3 </action>
即調用到PersonAction類中addPerson方法。PersonAction代碼如下:

1 public class PersonAction extends ActionSupport { 2 private Person person; 3 4 public Person getPerson() { 5 return person; 6 } 7 8 public void setPerson(Person person) { 9 this.person = person; 10 } 11 12 public String addPerson() { 13 // ... 14 return SUCCESS; 15 } 16 }
如上所述,即完成了一個添加Person的工作步。
但是若傳入的不是一個對象,而是一組對象呢?
不難想到,前端所需要改的部分即是input標簽中的name屬性。例如添加2個Person,前端修改如下:

1 <form action="addperson" method="post"> 2 <input type="text" name="person[0].name"> 3 <input type="number" min="0" max="200" name="person[0].age"> 4 <input type="text" name="person[1].name"> 5 <input type="number" min="0" max="200" name="person[1].age"> 6 <button type="submit"></button> 7 </form>
struts.xml其實是不需要改變的。需要改變的應該是PersonAction類。因為獲取的是一組Person,所以其中的變量應該也改為一組變量。即:

1 public class PersonAction extends ActionSupport { 2 private ArrayList<Person> person = new ArrayList<>(); // 這里一定需要分配,否則將提示空指針錯誤 3 4 public ArrayList<Person> getPerson() { 5 return person; 6 } 7 8 public void setPerson(ArrayList<Person> person) { 9 this.person = person; 10 } 11 12 public String addPerson() { 13 // ... 14 return SUCCESS; 15 } 16 }
但是此時,運行可知,並不可以正確的導入數據。原因大概是后台對傳入的數組無法識別數組中的每個元素是什么?
所以需要一個配置文件即PersonAction-conversion.properties。該文件需要放在與PersonAction所屬於的包同級的位置。
通過該配置文件說明數組中的元素的屬於的類。

Element_person=dao.Person CreateIfNull_person=true
配置文件的第一行說明了元素屬於的類的類型。
第二行說明若數組為空也創建該數組。
至此,即完成了Struts2提交對象數組至后台的操作。