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

JSP 頁面空指針異常排查:List 資料未正確傳遞至前台

     編輯:程式設計綜合問答

錯誤代碼關鍵點

// Servlet/Controller
List<BrandVO> listBrand = new ArrayList<>();
while (rs.next()) {
    BrandVO brand = new BrandVO();
    brand.setId(rs.getInt(\"id\"));
    brand.setBname(rs.getString(\"name\"));
    listBrand.add(brand);
}
req.setAttribute(\"carList\", rs.getInt(\"id\"));  // ❌ 錯誤:存入單個 Integer 而非 List
req.getRequestDispatcher(\"add_car.jsp\").forward(req, resp);

// JSP
<% List<BrandVO> listBrand = (List<BrandVO>) request.getAttribute(\"carList\");
for (BrandVO brand : listBrand) { %>  // ❌ NPE: carList 是 Integer,強轉失敗或為 null
    <option><%=brand.getBname()%></option>
<% } %>

核心錯誤

req.setAttribute(\"carList\", rs.getInt(\"id\")) 應為 req.setAttribute(\"carList\", listBrand)。
屬性名 carList 語意誤導,建議改為 brandList。

修正版 Servlet 代碼

List<BrandVO> brandList = new ArrayList<>();
while (rs.next()) {
    BrandVO brand = new BrandVO();
    brand.setId(rs.getInt(\"id\"));
    brand.setBname(rs.getString(\"name\"));
    brandList.add(brand);
}
req.setAttribute(\"brandList\", brandList);  // 正確存入 List
req.getRequestDispatcher(\"add_car.jsp\").forward(req, resp);

修正版 JSP 代碼(建議使用 JSTL/EL 避免腳本語)

<%@ taglib prefix=\"c\" uri=\"https://java.sun.com/jsp/jstl/core\" %>
<select name=\"brandId\">
    <c:forEach items=\"${brandList}\" var=\"brand\">
        <option value=\"${brand.id}\\">${brand.bname}</option>
    </c:forEach>
</select>

防禦性檢查(若仍可能為空)

<c:if test=\"${not empty brandList}\">
    <c:forEach ...>...</c:forEach>
</c:if>
<c:if test=\"${empty brandList}\">
    <option disabled>無品牌資料</option>
</c:if>

調試建議

  1. 在 Servlet 中 System.out.println(brandList.size()) 確認資料已查出。
  2. 瀏覽器開發者工具 Network 面板檢查回應 HTML 是否包含 <option>。
  3. 若使用框架,檢查攔截器/過濾器是否清空了 request 屬性。

總結

**屬性名稱拼寫錯誤、存入錯誤類型**是新手最常見錯誤。請養成:
1. 定義常量 public static final String ATTR_BRAND_LIST = \"brandList\"; 統一鍵名。
2. 使用 JSTL/EL 替代 Java 腳本語,編譯期發現類型錯誤。
3. 單元測試 Controller 確保 Model 屬性正確設置。

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