Struts2封装集合类型的数据
在实际开发中,有些时候我们需要批量的插入用户或者批量的插入其他对象,在Action中需要接受到这多个Action中封装的对象,然后传递给业务层,那么这个时候就需要将表单的数据封装到集合中,一般使用的集合是List或者是Map
封装到List集合中
- 编写前端form表单
<body>
<form action="${pageContext.request.contextPath }/listParamAction_get" method="post">
<!-- 注意:这里的name属性中的前缀-list必须与Action类中添加的List属性的名字一致 -->
用户名:<input type="text" name="list[0].username"></br>
密码:<input type="text" name="list[0].password"></br>
年龄:<input type="text" name="list[0].age"></br>
用户名:<input type="text" name="list[1].username"></br>
密码:<input type="text" name="list[1].password"></br>
年龄:<input type="text" name="list[1].age"></br>
<input type="submit" value="提交">
</form>
</body>
- 编写Action类
package com.zillion.action;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class ListParamAction extends ActionSupport{
//提供一个list属性,用于将页面的属性注入到list的user对象中
//这里的List属性的名称与表单name属性的前缀必须一致
private List<User> list;
public List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
public String get() throws Exception {
for(User user : list){
System.out.println(user);
}
return SUCCESS;
}
}
- action配置
<action name="listParamAction_*" class="com.zillion.action.ListParamAction" method="{1}">
<result name="success">/success.jsp</result>
</action>
- 结果
封装到Map集合中
- 编写前端form表单
<body>
<form action="${pageContext.request.contextPath }/mapParamAction_get" method="post">
用户名:<input type="text" name="map['one'].username"></br>
<!-- name属性的前缀必须与Action中的Map的对象名一致 -->
密码:<input type="text" name="map['one'].password"></br>
年龄:<input type="text" name="map['one'].age"></br>
用户名:<input type="text" name="map['two'].username"></br>
密码:<input type="text" name="map['two'].password"></br>
年龄:<input type="text" name="map['two'].age"></br>
<input type="submit" value="提交">
</form>
</body>
- 编写Action类
package com.zillion.action;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.opensymphony.xwork2.ActionSupport;
public class MapParamAction extends ActionSupport{
//Map的对象名必须与表单中的name属性名前缀一致
private Map<String, User> map;
public Map<String, User> getMap() {
return map;
}
public void setMap(Map<String, User> map) {
this.map = map;
}
public String get() throws Exception {
Set<String> keySet = map.keySet();
for (String key : keySet) {
User user = map.get(key);
System.out.println(user);
}
return SUCCESS;
}
}
- 配置Action
<action name="mapParamAction_*" class="com.zillion.action.MapParamAction" method="{1}">
<result name="success">/success.jsp</result>
</action>
- 结果