Monday, July 26, 2021

How to loop over HashMap in JSP using JSTL? Example

Though there are a number of ways to loop over a HashMap in JSP, or any other Map implementation e.g. Hashtable, I personally prefer the JSTL foreach tag for iteration over HashMap in JSP. As a Java programmer, you will often have a strong urge to use Java code directly in JSP using scriptlet, but that's a bad coding practice and one should always avoid that. In fact, by smart use of expression language and JSTL core tag library, you can reduce a lot of Java code from your JSP page. In our last post, we have seen an example of JSTL foreach tag to loop over List, but not a HashMap, and that creates a doubt in one of my readers mind that foreach tag doesn't support Map implementation like HashMap or Hashtable as they are not Collection, but that's not true.

You can use the same technique to loop over a HashMap in JSP which we have used earlier to loop over a list in JSP.

The JSTL foreach tag has special support for looping over Map, it provides you both key and value by using var attribute. In the case of HashMap, object exported using var contains Map.Entry object.

Since Map.Entry has getKey() and getValue() method, you can access them using expression language $(entry.key) and $(entry.value), as we will seen in our example. You can iterate over HashMap to create a table of key and value, or any HTML element e.g. <select>, which needs text and value.</select>



Looping over HashMap in JSP using JSTL

When we loop over an HashMap using JSTL foreach tag, it stores the current Map.Entry object into variable exported by var attribute of foreach tag. If var="entry" then $(entry.key} will give us key and $(entry.value) will return value, as shown in below example:

key = $(entry.key} and value = $(entry.value}

Just remember, In order to use JSTL core tag library, you need to include jstl.jar file in the classpath. This usually means copying jstl.jar into WEB-INF/lib folder of your project and import them using the taglib directive as <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>.

If you are not sure how classpath works in Java e.g. how exactly Servlet and JSP look for a class file in WEF-INF and META-INF folder, I suggest you reading the custom tag chapter from the Head First Servlet and JSP book. It has explained this concept very well.




Iterating a HashMap in JSP using JSTL foreach loop

Let's see a fully functional, code example of looping over HashMap in JSP. In this example, you will dynamically create a table with two columns, one for key and other for value, by using data stored in HashMap.

Though I have used scriptlet for embedding Java code into JSP for populating HashMap, you should not do that, it's just for demonstration purposes. In fact, the whole point of using JSTL and expression language is to avoid Java code in JSP, as Java code in JSP leads to a maintenance nightmare.

You can further join these Servlet and JSP Courses to learn more about advanced best practices to follow while developing a web application in the Java JEE platform.


Anyway, here is our sample JSP page

<%@page import="java.util.Hashtable"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.HashMap"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> How to Loop over Map i.e. HashMap or Hashtable in JSP 
                 - JSTL foreach tag example</title>
    </head>

    <body>  
        <h2> How to traverse HashMap in JSP</h2>

        <%
            // Avoid Java Code in JSP - This is only for ease of testing
            Map<Integer, String> numberToString = new HashMap<Integer, String>();
            numberToString.put(1, "JSP");
            numberToString.put(2, "Java");
            numberToString.put(3, "JSTL");
            numberToString.put(4, "J2EE");
            numberToString.put(5, "JEE");

            // put the hashmap as pageContext attribute
            pageContext.setAttribute("map", numberToString);
        %>


        <%-- JSTL foreach tag example to loop a HashMap in JSP --%>
        <table>
            <c:forEach var="entry" items="${pageScope.map}">
                <tr>
                    <td><c:out value="${entry.key}"/></td>
                    <td><c:out value="${entry.value}"/> </td>
                </tr>
            </c:forEach>
        </table>
        
         <h2> How to loop Hashtable in JSP</h2>

        <%
            // Avoid Java Code in JSP - This is only for ease of testing
            Map<String, Integer> prices = new Hashtable<String, Integer>();
            prices.put("Google", 500);
            prices.put("Apple", 300);
            prices.put("Amazon", 320);
            prices.put("BABA", 94);
            prices.put("MSFT", 30);

            // putting hashtable into pageContext variable
            pageContext.setAttribute("sharePrice", prices);
        %>


        <%-- JSTL foreach tag example to loop Hashtable in JSP --%>
        <table>
            <c:forEach var="entry" items="${pageScope.sharePrice}">
                <tr>
                 <td><c:out value="${entry.key}"/></td> 
                <td><c:out value="${entry.value}"/> </td>
                 </tr>
            </c:forEach>
        </table>

    </body>
</html>
Output:
How to traverse HashMap in JSP
1 JSP 
2 Java 
3 JSTL 
4 J2EE 
5 JEE 


Here is the actual HTML page created by this JSP  and how it will look like when you run your web application or deploy it on tomcat.

How to for loop HashMap and Hashtable in JSP with Example


That's all on How to loop or iterate a HashMap in JSP using JSTL foreach tag. JSTL core tag is a powerful tag and it not only supports iteration of Map like HashMap or Hashtable, but also any Collection class including List, Set and array. It's JSP best practice to use the JSTL and custom tags for all traversal, iteration, and looping needs, and try to avoid using Java code in JSP as much as possible.


Other JSP and JSTL Tutorials from Javarevisited Blog, you may like

If you want to learn more about Servlet and JSP I suggest you reading either Head First JSP and Servlet or Murach's Java Servlets and JSP book. Even though both are great books the latter one is more up-to-date and covers both JSP and Servlet in good detail, but the former one still provides the most enjoyable learning experience and beginners should use that one.

4 comments:

  1. Insted of using forEach tag, can we also use forTokens tag to iterate over HashMap in JSP?

    ReplyDelete
  2. I am trying to use JSTL tag library to iterate over a Map in JSP but getting compile time related to not able to find forEach tag. I have already included jstl.jar inside WEB-INF folder but still getting same error. Admin can you please help?

    ReplyDelete
  3. @Anonymous make sure to include the core taglib in your JSP like this:

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


    ReplyDelete
  4. Please, JSP is deprecated from java 6

    ReplyDelete