Use <c:forEach> with HashMap

JavaJspJstl

Java Problem Overview


I have a java class that sets an servlet attribute to a HashMap object:

request.setAttribute("types", da.getSecurityTypes());

where request is an HttpServletRequest Object, and da.getSecurityTypes() returns a HashMap Object.

Is there a way to go through the HashMap collection using c:foreach or some other JSTL tags?

I was thinking:

 <c:forEach var="type" items="${types}">
                 ...
     </c:forEach>

Or if it can't be done, how would one make a custom tag to process this?

Resorting to Java code in my JSP page is be my last resort and I'd like to know if this is possible with JSTL.

Thanks, Jonas.

Java Solutions


Solution 1 - Java

Yes, this is perfectly acceptable.

When you use <c:forEach> to iterate over a Map, each item in the iteration is an instance of Map.Entry. So given your example:

<c:forEach var="type" items="${types}">
   Key is ${type.key}
   Value is ${type.value}
</c:forEach>

Solution 2 - Java

It works, you'll have type.key and type.value to play with in the loop.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjonasespelitaView Question on Stackoverflow
Solution 1 - JavaskaffmanView Answer on Stackoverflow
Solution 2 - JavadavebView Answer on Stackoverflow