125

I'm looking to have JSTL loop through a Map<String, String> and output the value of the key and it's value.

For example I have a Map<String, String> which can have any number of entries, i'd like to loop through this map using JSTL and output both the key and it's value.

I know how to access the value using the key, ${myMap['keystring']}, but how do I access the key?

1

2 Answers 2

284

Like this:

<c:forEach var="entry" items="${myMap}">
  Key: <c:out value="${entry.key}"/>
  Value: <c:out value="${entry.value}"/>
</c:forEach>
2
  • 17
    Note to others: do not try to name var in forEach loop "param"
    – user11153
    Mar 6, 2014 at 9:59
  • How can i change the value dynamically withing forEach. Example. <c:forEach var="entry" items="${myMap}"> <!-- Change the entry.key and entry.value to some other value then the one coming from Map --> Key: <c:out value="${entry.key}"/> Value: <c:out value="${entry.value}"/> </c:forEach>
    – Sam
    May 30, 2020 at 7:32
6

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

6
  • 35
    Don't use scriplets. They are bad.
    – tad
    Aug 3, 2012 at 21:11
  • @tad I've also heard that. But why?
    – TJ-
    Oct 16, 2012 at 6:47
  • 7
    @TJ- As a general rule, there are few good reasons to put powerful logic in your templates; they are hard to debug, they mix paradigms, and they can produce unexpected results. Besides, the JSTL aready provides a facility to cleanly iterate over maps: the forEach tag.
    – tad
    Oct 16, 2012 at 17:55
  • 14
    @tad he's obviously using scriplets to set up his test data. This was a perfectly good answer
    – jk.
    Jul 11, 2014 at 18:54
  • 7
    @jk: I agree. The downvotes here are pretty ridic. Also, the idea that scriptlets can produce unexpected results makes no sense to me. They're not pretty, but 1+1 always equals 2, unless there are some specific scenarios I'm not aware of.
    – IcedDante
    Oct 16, 2014 at 19:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.