Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 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 Reply

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...