如何直接在地图的值上使用jstl foreach? [英] How to use jstl foreach directly over the values of a map?
问题描述
我尝试了以下令人惊讶的无效的方法,看起来.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
? - How to loop over a
Map
using<c:forEach>
?
See also:
这篇关于如何直接在地图的值上使用jstl foreach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!