Struts2之把数据封装到集合中

本文详细介绍如何在Struts2框架中使用集合类型(如List和Map)来封装和传递复杂参数,包括页面表单的编写方式和Action类的实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

封装复杂类型的参数(集合类型 Collection,Map接口等)
需求:页面中有可能想批量添加一些数据,就使用该技术。把数据封装到集合中
把数据封装到Collection中

  • 因为Collection接口都会有下标值,所有页面的写法会有一些区别,注意:
    <input type="text" name="products[0].name"/>
  • Action中的写法,需要提供products的集合,并且提供get和set方法

把数据封装到Map中

  • Map集合是键值对的形式,页面的写法
    <input type = "text" name="map['one'].name"/>
  • |Action中提供map集合,并且提供get和set方法
public class Regist4Action extends ActionSupport {
    private List<User> list;

    public List<User> getList() {
        return list;
    }

    public void setList(List<User> list) {
        this.list = list;
    }

    public String execute() throws Exception{
        for(User user :list){
            System.out.println(user);
        }
        return NONE;
    }
}
<h3>向List集合封装数据(默认采用属性驱动的方式)</h3>
<!--后台:List<User> list-->
<form action = "${pageContext.request.contextPath}/regist4.action" method="post">
    姓名:<input type="text" name="list[0].username"/><br/>
    密码:<input type="password" name="list[0].password"/><br/>
    年龄:<input type="password" name="list[0].age"/><br/>

    姓名:<input type="text" name="list[1].username"/><br/>
    密码:<input type="password" name="list[1].password"/><br/>
    年龄:<input type="password" name="list[1].age"/><br/>
    <input type="submit" value="注册">
</form>
  <!--把数据封装到list集合中-->
        <action name="regist4" class="com.zst.demo2.Regist4Action"/>

把数据封装到map集合中

<h3>向Map集合封装数据(默认采用属性驱动的方式)</h3>
<!--后台:Map<String ,User> map-->
<form action = "${pageContext.request.contextPath}/regist5.action" method="post">
    姓名:<input type="text" name="map['one'].username"/><br/>
    密码:<input type="password" name="map['one'].password"/><br/>
    年龄:<input type="password" name="map['one'].age"/><br/>
<!--自定义key值-->
    姓名:<input type="text" name="map['two'].username"/><br/>
    密码:<input type="password" name="map['two'].password"/><br/>
    年龄:<input type="password" name="map['two'].age"/><br/>
    <input type="submit" value="注册">
</form>
public class Regist5Action extends ActionSupport {
    private Map<String ,User> map;

    public Map<String, User> getMap() {
        return map;
    }

    public void setMap(Map<String, User> map) {
        this.map = map;
    }


    @Override
    public String execute() throws Exception {
        System.out.println(map);
        return NONE;
    }
}
  <!--把数据封装到Map集合中-->
        <action name="regist5" class="com.zst.demo2.Regist5Action"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值