// 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。
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);
<%@ 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>
System.out.println(brandList.size()) 確認資料已查出。<option>。**屬性名稱拼寫錯誤、存入錯誤類型**是新手最常見錯誤。請養成:
1. 定義常量 public static final String ATTR_BRAND_LIST = \"brandList\"; 統一鍵名。
2. 使用 JSTL/EL 替代 Java 腳本語,編譯期發現類型錯誤。
3. 單元測試 Controller 確保 Model 屬性正確設置。