用JSTL 怎么遍历Map中的实体类

如题所述

第1个回答  2009-09-11
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(1, "zhu");
map.put(2, "aa");
map.put(3, "bbb");
map.put(4, "ccc");
map.put(5, "ddd");
request.setAttribute("map", map);
request.getRequestDispatcher("/show.jsp").forward(request,response);
}

show.jsp

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

显示:
1 zhu
2 aa
3 bbb
4 ccc
5 ddd

每个 xx 代表一个key-value映射关系 也就是 Entry
Entry 有 getKey() 和 getVaue() 方法
所以 就 xx.key xx.value
.xx 就是调用getXx()方法

如果你的map 的value 里放的是 对象类型比如 一个person(JavaBean)的实例
如果有 name 属性 那么取得name属性 ${xx.value.name}
嵌套多少层没事,只要有get方法
第2个回答  2009-09-11
<c:forEach var="object" items="${userMap}">
<c:out value="${object.value.name}"></c:out>
<p>
</c:forEach>
参考这个
http://fengzhiyin.javaeye.com/blog/310939本回答被提问者采纳