在 JSP 中使用 JSTL <c:forEach> 遍歷 java.util.Map 是常見需求。本文詳細說明 EL 表達式存取 Map 的語法、var 變數類型為 Map.Entry 的原理、鍵值輸出方式,並提供巢狀 Map 遍歷實戰範例。
${map[key]} 或 ${map.key} 可取值 (key 為字串常數時)。<c:forEach items="${map}" var="entry"> 時,entry 類型為 java.util.Map.Entry<K,V>。Map.Entry 提供 getKey()、getValue(),EL 對應 ${entry.key}、${entry.value}。<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.*" %>
<%
Map<String, String> map2 = new HashMap<>();
map2.put("a", "hello world");
map2.put("b", "this is map");
request.setAttribute("map2", map2);
%>
<c:forEach var="entry" items="${map2}">
${entry.key} > ${entry.value} <br/>
</c:forEach>
輸出:
a > hello world b > this is map
<c:if test="${not empty item.product}">
<c:forEach items="${item.product}" var="product">
<c:if test="${product.key == 'userName'}">
${product.value}
</c:if>
</c:forEach>
</c:if>
item.product 為 Map<String, String> 或 List<Map.Entry>product.key、product.value 同理存取fn:length() 需引入 xmlns:fn="https://java.sun.com/jsp/jstl/functions"var="entry",改用 var="outerEntry"/var="innerEntry"。items="${map}" 若 map 為 null 會拋異常,建議 items="${empty map ? {} : map}" 或 Controller 端保證非 null。${map['key.name']} 括號語法。HashMap 無序,若需保持插入序請用 LinkedHashMap;需排序用 TreeMap。@GetMapping("/demo")
public String demo(Model model) {
Map<String, Object> data = new LinkedHashMap<>();
data.put("id", 1001);
data.put("name", "張三");
data.put("tags", Map.of("role", "admin", "level", "VIP")); // Java 9+ Map.of
model.addAttribute("userMap", data);
return "mapDemo";
}
掌握 <c:forEach items="${map}" var="entry">${entry.key} = ${entry.value}</c:forEach> 這一核心模式,配合 Map.Entry 的 getKey/getValue 對應 EL .key/.value,即可靈活處理各種 Map 遍歷需求。注意變數命名隔離、空值防護、Map 實現類選擇,即能寫出健壯的 JSP 視圖代碼。