Monday, March 30, 2015

How to loop a HashMap or Hashtable in JSP

How to loop a HashMap or Hashtable in JSP

Though there are number of ways to loop over HashMap in JSP, or any other Map implementation e.g. Hashtable, I personally prefer JSTL foreach tag for this. As a Java programmer, I often have urge to use Java code directly in JSP using scriptlet, but that's a bad coding practice, and one should always avoid that. Infact by smart use of expression language and JSTL core tag library, you can reduce lot of Java code from JSP. In our last post, we have seen example of JSTL foreach tag to loop over List, but not a Map, 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. JSTL foreach tag has special support for looping over Map, it provides you both key and value by using var attribute. In 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 Map to create table of key and value, or any HTML element e.g. <select>, which needs text and value.</select>


Looping Map in JSTL

When we loop over a Map using JSTL foreach tag, it stores 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 its JAR files in classpath, usually /WEB-INF/lib and import them using taglib tag as <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>.


Iterating a HashMap in JSP using JSTL foreach loop

Let's see a full functional, code example of looping over HashMap in JSP. We will create a table with two column, one for key and other for value, from Map data. Though, we have used scriptlet for embedding Java code into JSP, you should not do that, it's just for demonstration purpose. In fact, whole point of using JSTL and expression language is to avoid Java code in JSP, , it leads to maintenance nightmare.

<%@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 JSP page 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 e.g.. HashMap or Hashtable, but also any Collection class including List, Set and array. It's JSP best practice to use tag for all traversal, iteration and looping needs, and avoid using Java code in JSP.

No comments:

Post a Comment