3

I am new to JSP/JSTL.

I have set a HashMap on request as follows

HashMap <String, Vector> hmUsers = new HashMap<String, Vector>();

HashMap hmUsers = eQSessionListener.getLoggedinUsers();

request.setAttribute("currentLoggedInUsersMap", hmUsers);

I am alerting HashMap in My jsp as follows

<script> alert("<c:out value = '${currentLoggedInUsersMap}' />"); </script>

All works as per my expectations till now.

But if I try to get key of this HashMap as follow then nothing is alerted.

<script> alert("<c:out value = '${currentLoggedInUsersMap.key}' />"); </script>

Is there anything I am going wrong?

Thanks in advance.

Braj
  • 46,415
  • 5
  • 60
  • 76
Sachin
  • 247
  • 4
  • 16
  • 26

2 Answers2

6

This is what you need to iterate the Map in JSP. For more info have a look at JSTL Core c:forEach Tag.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:forEach items="${currentLoggedInUsersMap}" var="entry">
    Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>

It's just like a Map.Entry that is used in JAVA as shown below to get the key-value.

for (Map.Entry<String, String> entry : currentLoggedInUsersMap.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
}

Read detained description here on How to loop through a HashMap in JSP?

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
2

You can iterate over hashmap as:

    <c:forEach items="${currentLoggedInUsersMap}" var="usersMap" varStatus="usersMapStatus">  
        //Key
        Key: ${usersMap.key}
        //Iterate over values ,assuming vector of strings
        <c:forEach items="${usersMap.value}" var="currentLoggedInUserValue" varStatus="valueStatus">
            Value: ${currentLoggedInUserValue}
        </c:forEach>        
    </c:forEach>

Here ${usersMap.key} is the list of keys present in the map and ${usersMap.value} is the vector which you have to iterate again in an inner loop as shown above.

Make sure to import:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Prasad
  • 3,785
  • 2
  • 14
  • 23