Struts2把数据封装到集合中之封装到Collection中


数据封装到集合中,可以封装到集合中,也可以封装到Map中。该篇博客主要讲解数据封装到集合中的封装到Collection中。

1. 封装复杂类型的参数(集合类型 Collection 、Map接口等) 2. 需求:页面中有可能想批量添加一些数据,那么现在就可以使用上述的技术了。把数据封装到集合中 3. 把数据封装到Collection中(单元素集合)封装到集合集合中可以存储多条数据 * 因为Collection接口都会有下标值,所有页面的写法会有一些区别,注意: > <input type="text" name="products[0].name" /> product为集合的名字 * 在Action中的写法,需要提供products的集合,并且提供get和set方法。

以封装到list集合为例:
1.创建javaBean类User:
package com.huida.domain;

public class User {
    
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password + "]";
    }
    
    
}

2.创建action类RegistAction:这里的写法与封装数据的属性封装写法类似:定义属性(注意这里不需要实例化),然后定义set和get方法即可。

package com.huida.action1;

import java.util.List;

import com.huida.domain.User;
import com.opensymphony.xwork2.ActionSupport;

public class Regist4Action extends ActionSupport{
    
    List<User> list;//这里list作为属性,不需要new实例
    //定义Set和get方法
    
    public List<User> getList() {
        return list;
    }

    public void setList(List<User> list) {
        this.list = list;
    }
    
    @Override
    public String execute() throws Exception {
        
        for(User user:list){
            //如果成功就会输出
            System.out.println(user);
        }
        return NONE;
    }

    
}

3.对action在struts.xml中进行配置:

<package name="demo" namespace="/" extends="struts-default">
        <action name="regist4Action" class="com.huida.action1.Regist4Action"></action>
    </package>

4.书写表单,因为集合可以封装多条数据,所以这里在表单中多写几条记录:这里还要注意name中值的写法:list[0].username

<h3>数据封装到list集合中</h3>
    <!-- 将数据封装到集合中,可以封装多条数据,所以我们在这里多写几个记录 -->
    <form action="${ pageContext.request.contextPath }/regist4Action.action" method="post"> 
        姓名<input type="text" name="list[0].username"/><br/>
        密码<input type="text" name="list[0].password"/><br/>
        姓名<input type="text" name="list[1].username"/><br/>
        密码<input type="text" name="list[1].password"/><br/>
        <input type="submit" value="注册">

注意:表单请求跳转的页面(regist4Action.action)应该与struts.xml配置文件中action标签中name对应的值相同,否则会出现资源找不到的错误。

启动服务器,运行index.jsp页面,在表单中输入姓名和密码,点击注册,会在控制台输出如下内容表示封装数据成功:

所以我们可以利用集合来对数据进行批量处理(批量加载,批量删除)。

 
原文地址:https://www.cnblogs.com/wyhluckdog/p/10106589.html