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>

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>

Happy iterating :-)

Get our Articles via Email. Enter your email address.

You may also like...

20 Comments

  1. OOH that’s great !!! surely this code will help me a lot … thanks

  2. KanyTheCoder says:

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

  3. KanyTheCoder says:

    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…..?

  4. prasad says:

    in first foreach loop u missed to items=”${cityList}” k

  5. Gura says:

    I attempted using your hashmap example. In the jsp

    //JSP

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

    However this does not work.

    • Deepti says:

      @Gura : add in jsp and try if it works

    • Deepti says:

      sorry i missed code —- add

    • Deepti says:
      <%@ page isELIgnored="false" %>
      <%@ page isELIgnored="false" %>
      
  6. Shammi says:

    Thanks

  7. Sudipta says:

    Thanks man..your blogs helped me a lot..thank you once again..

  8. Daniel says:

    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:

  9. Pannaga says:
    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;
    	}
    
    }
    

    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

    • Rodislav says:

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

  10. Dhande says:

    Thanks…

  11. satish says:

    If that Map is present in one method like below.

    @ModelAttribute("categoriesList")
    	public Map populateCategoryList() {
    		Map categoryMap = new LinkedHashMap();
    		try {
    			logger.debug("Call to programResourceService to get all the categoriesList ");
    			List articleCategory = service.getCategory();
    			logger.debug("got the category list of size::"+articleCategory.size());
    			//categoryMap.put("0", "Select a Category");
    			for (int i = 0; i &lt; articleCategory.size(); i++) {
    				CategoriesForm categoryForm = (CategoriesForm) articleCategory
    						.get(i);
    				logger.debug(&quot;Category Id and Name ::&quot;+categoryForm.getCategoryId().toString() +&quot; :: &quot;+categoryForm.getCategoryName());
    				categoryMap.put(categoryForm.getCategoryId().toString(),
    						categoryForm.getCategoryName());
    			}
    			logger.debug(&quot;Contruced categories form list and the size is : &quot;+articleCategory.size());
    		} catch (Exception e) {
    			logger.error(&quot;Error while getting the categories List&quot;,e);
    		}
    		return categoryMap;
    	}
    

    how to get the values key and value to a select box…?

  12. Daya says:

    Hi All,
    can any one please help me out that are there any chances were in we can remove hash map key/value pair through JSTL

    below is the piece of code,

    ${a.key}

    now we have got the MAP key, can we remove this key from existing Map

    Thanks
    Daya

  13. Deepak Kataria says:

    Is it possible to iterate over arrays?

  14. prasad says:

    thank you,but my map value is Object type..could you please tell me how can i iterate my object values in jsp

  15. Binh Thanh Nguyen says:

    Thanks, nice tips

  16. eek says:

    Iterating through map is bugged. It iterates successfully if there is only 1 static map. However, if map changes dynamically, let’s say by selecting an item from dropdown menu, a new map is generated for iteration, then c:foreach tries to use the first map for iteration which results in incorrect data..

Leave a Reply

Your email address will not be published. Required fields are marked *