在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的命名約定。
Java代碼
- <%
- Map<String,String> map2 = new HashMap();
- map2.put("a","hello world");
- map2.put("b","this is map");
- request.setAttribute("map2",map2);
- %>
鍵值對遍歷
Java代碼
- <c:forEach var="item" items="${map2}">
- ${item.key} > ${item.value} <br>
- </c:forEach>
鍵遍歷
Java代碼
- <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>
----------------------------------------------------------------------------------------------
1、java map的便利取值
- Map<String,String> map = new HashMap<String,String>();
- map.put("key1", "value1");
- map.put("key2", "value2");
- Iterator<Entry<String,String>> iter = map.entrySet().iterator();
- while(iter.hasNext()) {
- Entry<String, String> entry = iter.next();
- System.out.println(entry.getKey()+"," + entry.getValue());
- }
- Set<Map.Entry<String, String>> entry = map.entrySet();
- for(Map.Entry<String, String> e : entry) {
- System.out.println(e.getKey()+"," + e.getValue());
- }
2、jstl的迭代取值
當forEach 的items屬性中的表達式的值是java.util.Map時,則var中命名的變量的類型就是 java.util.Map.Entry。這時var=entry的話,用表達式${entry.key}取得鍵名。
用表達式${entry.value}得到每個entry的值。這是因為java.util.Map.Entry對象有getKey和getValue方法,表達式語言遵守JavaBean的命名約定
- <c:forEach items="${map}" var="entry">
- <c:out value="${entry.key}" />
- <c:out value="${entry.value}" />
- </c:forEach>
3、jstl根據key取值
一、如果知道key值,${map.key1}
二、如果key值是個變量, 則${map[key]}, 使用數組訪問方式,同樣也可以用在知道key ${map["key1"]}