中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
复杂数据的封装有两种形式:(1)封装成List集合(2)封装成Map集合
1、封装成List集合
JSP代码:
<h3>封装到List集合中</h3> <form action="${ pageContext.request.contextPath }/productAction1.action" method="post"> 商品0名称:<input type="text" name="list[0].name"><br /> 商品0价格:<input type="number" name="list[0].price"><br /> 商品1名称:<input type="text" name="list[1].name"><br /> 商品1价格:<input type="number" name="list[1].price"><br /> 商品2名称:<input type="text" name="list[2].name"><br /> 商品2价格:<input type="number" name="list[2].price"><br /> <input type="submit" value="提交"> </form> <hr />
Action类代码:
package com.pipi.struts2.demo3; import com.opensymphony.xwork2.ActionSupport; import java.util.List; // Struts2中复杂数据的封装:封装到List集合中 public class ProductAction1 extends ActionSupport { // 封装定义一个List集合属性 private List<Product> listProduct; // 提供setter and getter public void setProducts(List<Product> products) { this.listProduct = products; } public List<Product> getProducts() { return listProduct; } @Override public String execute() throws Exception { // 接收数据 for (Product p : listProduct) { System.out.println(p); } return NONE; } }
2、封装成Map集合
<h3>封装到Map集合中</h3> <form action="${ pageContext.request.contextPath }/productAction2.action" method="post"> 商品0名称:<input type="text" name="map['key0'].name"><br /> 商品0价格:<input type="number" name="map['key0'].price"><br /> 商品1名称:<input type="text" name="map['key1'].name"><br /> 商品1价格:<input type="number" name="map['key1'].price"><br /> 商品2名称:<input type="text" name="map['key2'].name"><br /> 商品2价格:<input type="number" name="map['key2'].price"><br /> <input type="submit" value="提交"> </form> <hr />
package com.pipi.struts2.demo3; import com.opensymphony.xwork2.ActionSupport; import java.util.Map; // Struts2中复杂数据的封装:封装到Map集合中 public class ProductAction2 extends ActionSupport { // 封装定义一个Map集合 Map<String, Product> map; // 提供setter and getter public Map<String, Product> getMap() { return map; } public void setMap(Map<String, Product> map) { this.map = map; } @Override public String execute() throws Exception { // 接收数据 for (String key : map.keySet()) { Product value = map.get(key); System.out.println(key + "--- " + value); } return NONE; } }
作者:pipizhen_
来源:CSDN
微信扫码分享