How to use jstl foreach directly over the values o

2020-02-05 13:38发布

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.

标签: jsp jstl
3条回答
Bombasti
2楼-- · 2020-02-05 13:56

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:

查看更多
Emotional °昔
3楼-- · 2020-02-05 13:58

Also you can use this type if necessary

<c:forEach var="key" items="${theMap.keySet()}" varStatus="keyStatus">
    <c:set var="value" value="${theMap[key]}" />
</c:forEach>
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-05 14:16

you can iterate a map in jstl like following

<c:forEach items="${numMap}" var="entry">
  ${entry.key},${entry.value}<br/>
</c:forEach>
查看更多
登录 后发表回答