首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JSP Session 傳遞 List 物件並在另一頁面用 JSTL 遍歷輸出

     編輯:程式設計疑難解答

在 Servlet 中將 `List<Bean>` 放入 `session`,轉向 JSP 時用 `` 遍歷輸出。常見錯誤是 `items` 屬性寫成字串 `"rs"` 而非 EL 表達式 `${rs}`,導致 JSTL 當成字串逐字遍歷。本文給出正確寫法與完整範例。

錯誤代碼分析

<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>

完整 Servlet → JSP 流程範例

1. Bean 類別

public class ShopBean implements Serializable {
    private String sShopName;
    private String iNumbHj;
    private String rMoneyHj;
    // getter/setter 省略
}

2. Servlet 處理邏輯

@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");                  // 重導向
    }
}

3. 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` 避免佔用記憶體

替代方案:Request 轉發(較輕量)

// 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 即可零錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved