如何从存储在Session的ArrayList<Object[]>中获取并解析数据?
修正类型转换错误并正确输出ArrayList中的数据
首先得指出你现在的核心问题:你把存储Object[]的ArrayList错误转成了ArrayList<String>,这会直接导致ClassCastException——因为每个元素根本不是String,而是Object[]数组。所以第一步必须修正类型转换,然后才能正确遍历输出数据。
方案一:使用Java脚本(和你原代码风格一致)
先把session中的对象转成正确的类型,再遍历每个数组元素拼接格式:
<% // 修正类型转换:转成ArrayList<Object[]>,和你存入session的类型一致 ArrayList<Object[]> custInfo = (ArrayList<Object[]>) session.getAttribute("custInfo"); // 先做非空判断,避免空指针异常 if (custInfo != null && !custInfo.isEmpty()) { int customerNum = 1; for (Object[] customerData : custInfo) { // 从数组中取出对应字段,转成String(因为你存的本来就是String) String loginId = (String) customerData[0]; String customerId = (String) customerData[1]; String requestDate = (String) customerData[2]; String updateUser = (String) customerData[3]; // 按要求格式输出 out.printf("customer%d-%s, %s, %s, %s%n", customerNum, loginId, customerId, requestDate, updateUser); customerNum++; } } %>
方案二:使用JSTL标签(更推荐的JSP写法,避免脚本)
如果你的项目引入了JSTL,可以用更简洁的标签写法,代码更易维护:
首先在JSP顶部引入JSTL核心标签库:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
然后直接遍历输出:
<c:if test="${not empty custInfo}"> <c:forEach items="${custInfo}" var="data" varStatus="loopStatus"> customer${loopStatus.count}- ${data[0]}, ${data[1]}, ${data[2]}, ${data[3]}<br> </c:forEach> </c:if>
loopStatus.count会自动生成从1开始的序号,正好对应你要的customer1、customer2...- JSTL会自动处理数组元素的类型转换(因为你存入的都是String类型),不用手动强转。
注意事项
- 必须修正类型转换:如果坚持用
ArrayList<String>,遍历的时候会抛出ClassCastException,因为每个元素是Object[]而非String。 - 空值处理:如果数据库字段可能为null,可以在取值时加入判断,比如
loginId = (customerData[0] == null) ? "N/A" : (String) customerData[0];,或者在JSTL中用${empty data[0] ? 'N/A' : data[0]}。
内容的提问来源于stack exchange,提问作者rameeza qureshi
相关产品推荐
相关产品推荐

