Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
803 views
in Technique[技术] by (71.8m points)

jsp - How to use jstl foreach directly over the values of a map?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...