JSTL对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的命名约定。

Java代码 复制代码 收藏代码
  1. <%  
  2. Map<String,String> map2 = new HashMap();  
  3. map2.put("a","hello world");  
  4. map2.put("b","this is map");  
  5. request.setAttribute("map2",map2);  
  6. %>  
<% 
Map<String,String> map2 = new HashMap(); 
map2.put("a","hello world"); 
map2.put("b","this is map"); 
request.setAttribute("map2",map2); 
%> 

键值对遍历

Java代码 复制代码 收藏代码
  1. <c:forEach var="item" items="${map2}">  
  2. ${item.key} > ${item.value} <br>  
  3. </c:forEach> 
<c:forEach var="item" items="${map2}"> 
${item.key} > ${item.value} <br> 
</c:forEach>

键遍历

Java代码 复制代码 收藏代码
  1. <c:forEach var="item" items="${map2}">  
  2. ${item.key}<br>  
  3. </c:forEach> 
<c:forEach var="item" items="${map2}"> 
${item.key}<br> 
</c:forEach>

值遍历

Java代码 复制代码 收藏代码
  1. <c:forEach var="item" items="${map2}">  
  2. ${item.value}<br>  
  3. </c:forEach>  
  4. <body>  
<c:forEach var="item" items="${map2}"> 
${item.value}<br> 
</c:forEach> 
<body> 

Java代码 复制代码 收藏代码
  1. <%  
  2. List<String> list = new ArrayList<String>();  
  3. list.add("first");  
  4. list.add("second");  
  5. List<String> list2 = new ArrayList<String>();  
  6. list2.add("aaaaaa");  
  7. list2.add("bbbbbb");  
  8. Map<String,List<String>> map = new HashMap();  
  9. map.put("a",list);  
  10. map.put("b",list2);  
  11. request.setAttribute("map",map);  
  12. %>  
<% 
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); 
%> 

通过键获得列表值,并遍历列表

Java代码 复制代码 收藏代码
  1. <c:forEach var="item" items="${map['a']}">  
  2. ${item }<br>  
  3. </c:forEach><br>  
  4. <c:forEach var="item" items="${map['b']}">  
  5. ${item }<br>  
  6. </c:forEach> 
<c:forEach var="item" items="${map['a']}"> 
${item }<br> 
</c:forEach><br> 
<c:forEach var="item" items="${map['b']}"> 
${item }<br> 
</c:forEach>

map中值为列表,直接遍历列表中的每一项

Java代码 复制代码 收藏代码
  1. <c:forEach var="item" items="${map}">  
  2. <c:forEach items="${item.value}" var="it">  
  3. ${it }<br>  
  4. </c:forEach>  
  5. </c:forEach> 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值