How to iterate HashMap using JSTL forEach loop

JavaServer Tag library is one of the most used JSP tag library out there. I have used it almost in all of my JEE based projects. The best feature probably is the Iterator API in JSTL tag library. Here is a small code snippet which you might not know. Its very easy to iterate Lists using JSTL. For example:
//Java List<String> cityList = new ArrayList<String>(); cityList.add("Washington DC"); cityList.add("Delhi"); cityList.add("Berlin"); cityList.add("Paris"); cityList.add("Rome"); request.setAttribute("cityList", cityList); //JSP <c:forEach var="city" items="cityList"> <b> ${city} </b> </c:forEach>
Code language: Java (java)
But what if you want to iterate a Hashmap? Well that too is piece of cake. Here is the example:
//Java Map<String, String> countryCapitalList = new HashMap<String, String>(); countryCapitalList.put("United States", "Washington DC"); countryCapitalList.put("India", "Delhi"); countryCapitalList.put("Germany", "Berlin"); countryCapitalList.put("France", "Paris"); countryCapitalList.put("Italy", "Rome"); request.setAttribute("capitalList", countryCapitalList); //JSP <c:forEach var="country" items="${capitalList}"> Country: ${country.key} - Capital: ${country.value} </c:forEach>
Code language: Java (java)
Happy iterating :-)

View Comments

  • What if you use in the jsp file? How will the code be altered then and how does that work.....?

  • What I meant was this:

    What if you use jsp:useBean in the jsp file? How will the code be altered then and how does that work…..?

  • I attempted using your hashmap example. In the jsp

    //JSP

    Country: ${entry.key} - Capital: ${entry.value}

    However this does not work.

  • Thank you for this info! But you can actually get access to the value by just using the key, like if it was an array:

  • [code language="java"]
    public class StmtController extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    RequestDispatcher rd;
    HttpSession s=req.getSession();
    CustDTO cust=(CustDTO) s.getAttribute("cust");
    int accn=cust.getAccno();
    try {
    ArrayList a=new ArrayList();
    DesDAO d=new DesDAO();
    a=d.getStmt(accn);

    req.setAttribute("list", a);
    rd=req.getRequestDispatcher("stmt.jsp");
    rd.forward(req, resp);

    } catch (SQLException e) {
    resp.sendRedirect("error.html");
    }

    }
    }

    This is my servlet.

    package com.pannagaOrg.mvcBankApp.dto;

    public class DesDTO {
    private String descr;
    private String dt;
    private int accno;
    public int getAccno() {
    return accno;
    }
    public void setAccno(int accno) {
    this.accno = accno;
    }
    public String getDescr() {
    return descr;
    }
    public void setDescr(String descr) {
    this.descr = descr;
    }
    public String getDt() {
    return dt;
    }
    public void setDt(String dt) {
    this.dt = dt;
    }

    }
    This is my DTO

    package com.pannagaOrg.mvcBankApp.dao;

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;

    import com.pannagaOrg.mvcBankApp.dto.CustDTO;
    import com.pannagaOrg.mvcBankApp.dto.DesDTO;
    import com.pannagaOrg.mvcBankApp.utility.DBSingleton;

    public class DesDAO {

    public ArrayList getStmt(int accn) throws SQLException
    {
    ArrayList desList=new ArrayList();
    String query="SELECT * FROM bank.trans WHERE accno=?";
    DBSingleton conObj=DBSingleton.getConnectionObject();
    Connection con=conObj.getCon();
    PreparedStatement pstmt=con.prepareStatement(query);

    pstmt.setInt(1,accn);
    ResultSet res = pstmt.executeQuery();

    while(res.next())
    {
    String des=res.getString(3);
    String dt = res.getString(4);
    DesDTO d=new DesDTO();
    d.setDescr(des);
    d.setDt(dt);
    desList.add(d);
    }
    return desList;
    }

    }
    [/code]
    This is my DAO

    Insert title here

    click here to see statement:

    accn

    description

    date

    Here is my jsp

    But i am getting an exception
    org.apache.jasper.JasperException: An exception occurred processing JSP page /stmt.jsp at line 19

    16:
    17:
    18: accn
    19:
    20:
    21:
    22:

    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:401)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

    root cause

    javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:862)

    Please help me

    • Hi, it seems that you are using jetty, I propose you to switch to tomcat :) or move scriplet code in controller / servlet

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago