如何直接在地图的值上使用jstl foreach? [英] How to use jstl foreach directly over the values of a map?

查看:69
本文介绍了如何直接在地图的值上使用jstl foreach?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下令人惊讶的无效的方法,看起来.values在jstl中根本无效:

I tried the following which surprisingly does not work, looks like .values does not work at all in jstl:

<c:forEach var="r" items="${applicationScope['theMap'].values}">

映射是这样定义的(后来保存到ServletContext中):

The map is defined like this (and later saved to the ServletContext):

Map<Integer, CustomObject> theMap = new LinkedHashMap<Integer, CustomObject>();

如何使它工作?实际上,我真的很想避免修改foreach循环中的内容.

How to get this working? I actually really would like to avoid modifying what's inside of the foreach-loop.

推荐答案

所以您要遍历地图值? Map没有getValues()方法,因此您的尝试不起作用. <c:forEach>提供了 Map.Entry 返回具有getKey()getValue()方法的每个迭代.因此,应该执行以下操作:

So you want to iterate over map values? Map doesn't have a getValues() method, so your attempt doesn't work. The <c:forEach> gives a Map.Entry back on every iteration which in turn has getKey() and getValue() methods. So the following should do:

<c:forEach var="entry" items="${theMap}">
    Map value: ${entry.value}<br/>
</c:forEach>

从EL 2.2开始,由于新增了对调用非getter方法的支持,因此您可以直接调用Map#values():

Since EL 2.2, with the new support for invoking non-getter methods, you could just invoke Map#values() directly:

<c:forEach var="value" items="${theMap.values()}">
    Map value: ${value}<br/>
</c:forEach>

另请参见:

  • 如何使用<c:forEach>遍历Map?
  • See also:

    • How to loop over a Map using <c:forEach>?
    • 这篇关于如何直接在地图的值上使用jstl foreach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆