jstl EL表達式遍歷Map

在EL中,方括號運算符用來檢索數組和集合的元素。對於實現 java.util.Map 接口的集合,方括號運算符使用關聯的鍵查找存儲在映射中的值。
在方括號中指定鍵,並將相應的值作爲表達式的值返回。例如,表達式 ${map['key']} 返回與 map標識符所引用的 Map 中的 "key" 鍵相關聯的值。
當forEach 的items屬性中的表達式的值是java.util.Map時,則var中命名的變量的類型就是 java.util.Map.Entry。這時var=entry的話,用表達式${entry.key}取得鍵名。 用表達${entry.value}得到每個entry的值。這是因爲java.util.Map.Entry對象有getKey和getValue方 法,表達式語言遵守JavaBean的命名約定。

<% 
Map<String,String> map2 = new HashMap(); 
map2.put("a","hello world"); 
map2.put("b","this is map"); 
request.setAttribute("map2",map2); 
%> 

 鍵值對遍歷

<c:forEach var="item" items="${map2}"> 
${item.key} > ${item.value} <br> 
</c:forEach>

 鍵遍歷

<c:forEach var="item" items="${map2}"> 
${item.key}<br> 
</c:forEach>

 值遍歷

<c:forEach var="item" items="${map2}"> 
${item.value}<br> 
</c:forEach> 
<body> 

 

<% 
List<String> list = new ArrayList<String>(); 
list.add("first"); 
list.add("second"); 
List<String> list2 = new ArrayList<String>(); 
list2.add("aaaaaa"); 
list2.add("bbbbbb"); 
Map<String,List<String>> map = new HashMap(); 
map.put("a",list); 
map.put("b",list2); 
request.setAttribute("map",map); 
%> 

 

通過鍵獲得列表值,並遍歷列表

 

<c:forEach var="item" items="${map['a']}"> 
${item }<br> 
</c:forEach><br> 
<c:forEach var="item" items="${map['b']}"> 
${item }<br> 
</c:forEach>

 map中值爲列表,直接遍歷列表中的每一項

<c:forEach var="item" items="${map}"> 
<c:forEach items="${item.value}" var="it"> 
${it }<br> 
</c:forEach> 
</c:forEach>

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章