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}">
The map is defined like this (and later saved to the ServletContext):
Map<Integer, CustomObject> theMap = new LinkedHashMap<Integer, CustomObject>();
How to get this working? I actually really would like to avoid modifying what's inside of the foreach-loop.
You can use the same technique to loop over a HashMap in JSP which we have used earlier to loop over a list in JSP. The JSTL foreach tag has special support for looping over Map, it provides you both key and value by using var attribute. In the case of HashMap, object exported using var contains Map. Entry object.
You can use JSTL <c:forEach> tag to iterate over arrays, collections and maps. In case of arrays and collections, every iteration the var will give you just the currently iterated item right away. In case of maps, every iteration the var will give you a Map.
The varStatus variables give the user the means to refer to: the first row/node returned by a ForEach Tag; the last row/node returned by a ForEach Tag; the count of the current row/node returned by a ForEach Tag; and the index of the current row/node returned by a ForEach Tag.
JSTL foreach tag allows you to iterate or loop Array List, HashSet or any other collection without using Java code. After the introduction of JSTL and expression language(EL) it is possible to write dynamic JSP code without using scriptlet which clutters jsp pages.
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>
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>
Map
using <c:forEach>
?If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With