在 Servlet 中將 `List<Bean>` 放入 `session`,轉向 JSP 時用 `
<c:forEach items="rs" var="user"> <!-- ❌ 錯誤:items 是字串 "rs",會遍歷 'r'、's' 兩個字元 -->
<c:out value="${user.sShopName}"/>
</c:forEach>
<c:forEach items="${rs}" var="user"> <!-- ✅ 正確:EL 表達式取得 session 屬性 rs -->
<c:out value="${user.sShopName}"/>
</c:forEach>
public class ShopBean implements Serializable {
private String sShopName;
private String iNumbHj;
private String rMoneyHj;
// getter/setter 省略
}
@WebServlet("/queryShops")
public class QueryShopsServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<ShopBean> list = new ArrayList<>();
// 假設從資料庫查詢
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT sShopName, iNumbHj, rMoneyHj FROM shops");
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
ShopBean bean = new ShopBean();
bean.setSShopName(rs.getString("sShopName"));
bean.setINumbHj(rs.getString("iNumbHj"));
bean.setRMoneyHj(rs.getString("rMoneyHj"));
list.add(bean); // ✅ 每筆資料 new 一個 Bean
}
} catch (SQLException e) { throw new ServletException(e); }
req.getSession().setAttribute("shopList", list); // 放入 session
resp.sendRedirect("result.jsp"); // 重導向
}
}
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<html><body>
<table border="1">
<tr><th>店名</th><th>數量</th><th>金額</th></tr>
<c:forEach items="${shopList}" var="bean">
<tr>
<td><c:out value="${bean.sShopName}"/></td>
<td><c:out value="${bean.iNumbHj}"/></td>
<td><c:out value="${bean.rMoneyHj}"/></td>
</tr>
</c:forEach>
</table>
</body></html>
| 問題 | 正確做法 |
|---|---|
| `items` 屬性值 | 必須用 EL:`${sessionScope.shopList}` 或 `${shopList}` |
| Bean 重複使用 | 迴圈中**每筆 `new Bean()`**,否則 List 全是同一物件參考 |
| Session 取值範圍 | JSTL 隱含物件 `sessionScope`,`${sessionScope.shopList}` 明確指定 |
| 中文亂碼 | 頁面 `<%@ page pageEncoding="UTF-8" %>`、Servlet `resp.setCharacterEncoding("UTF-8")` |
| 資料量大 | 考慮分頁、或用 `request` 轉發而非 `session` 避免佔用記憶體 |
// Servlet
req.setAttribute("shopList", list); // 放入 request
req.getRequestDispatcher("/result.jsp").forward(req, resp); // 轉發
// JSP 同樣用 ${shopList} 即可(requestScope 隱含)
核心口訣:**`items="${list}"` 用 EL 取值、迴圈內 `new Bean()`、優先用 `request` 轉發**。掌握這三點,JSP Session/JSTL 遍歷 List 即可零錯誤。