Struts2之提交对象数组至后台

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 }
View Code

则前端对应的表单写法如下

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>
View Code

这个时候前端提交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>
View Code

即调用到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 }
View Code

如上所述,即完成了一个添加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>
View Code

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 }
View Code

但是此时,运行可知,并不可以正确的导入数据。原因大概是后台对传入的数组无法识别数组中的每个元素是什么

所以需要一个配置文件即PersonAction-conversion.properties。该文件需要放在与PersonAction所属于的包同级的位置。

通过该配置文件说明数组中的元素的属于的类。

Element_person=dao.Person
CreateIfNull_person=true
View Code

配置文件的第一行说明了元素属于的类的类型。

第二行说明若数组为空也创建该数组。

至此,即完成了Struts2提交对象数组至后台的操作。

原文地址:https://www.cnblogs.com/wsy06/p/5702115.html