风人园

弱水三千,只取一瓢,便能解渴;佛法无边,奉行一法,便能得益。
随笔 - 99, 文章 - 181, 评论 - 56, 引用 - 0
数据加载中……

JSTL--foreach 迭代Map对象(ZT)


以前都用forEach标签迭代List,Set对象,今天需要用它来迭代Map对象,就研究了一下。

以下是试验代码:

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.util.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
</head>
<%!
 public static class TTT{
  private String name;
  public TTT(String name){
   this.name = name;
  }
  public String getName(){
   return name;
  }
 }
%>
<%
 Map map = new LinkedHashMap();
 map.put(new TTT("111"),"aaaaaa");
 map.put(new TTT("222"),"bbbbbb");
 request.setAttribute("map",map);
%>
<body>
<c:forEach items="${map}" var="item">
${item.key.name}-${item.value}<br/>
</c:forEach>
</body>
</html>

item内保存的是java.util.Map.Entry对象这个对象有getKey,setKey,getValue,setValue方法,这样就可以在forEach内部使用map的key和value了。

posted on 2007-02-06 13:54 风人园 阅读(4195) 评论(0)  编辑  收藏 所属分类: Web