Use <c:forEach> with HashMap in java

Use <c:forEach> with HashMap in java

In a Java web application using JavaServer Pages (JSP) and the JSTL (JavaServer Pages Standard Tag Library), you can use the <c:forEach> tag to iterate over the entries of a HashMap. Here's an example of how to do it:

Assuming you have a servlet that adds a HashMap to the request attribute in your Java servlet code:

import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String> hashMap = new HashMap<>(); hashMap.put("key1", "value1"); hashMap.put("key2", "value2"); hashMap.put("key3", "value3"); request.setAttribute("myHashMap", hashMap); RequestDispatcher view = request.getRequestDispatcher("your_jsp_page.jsp"); view.forward(request, response); } } 

Now, you can use the <c:forEach> tag in your JSP page (your_jsp_page.jsp) to iterate over the entries of the HashMap:

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <title>Iterating over a HashMap</title> </head> <body> <h1>Iterating over a HashMap</h1> <table border="1"> <tr> <th>Key</th> <th>Value</th> </tr> <c:forEach var="entry" items="${myHashMap}"> <tr> <td><c:out value="${entry.key}" /></td> <td><c:out value="${entry.value}" /></td> </tr> </c:forEach> </table> </body> </html> 

In this JSP example:

  • We include the JSTL core taglib with the <%@ taglib %> directive.
  • We use the <c:forEach> tag to iterate over the entries of the myHashMap attribute, which we set in the servlet.
  • Inside the loop, we use ${entry.key} and ${entry.value} to access the key and value of each entry in the HashMap.

When you access the servlet, it forwards the request to the JSP page, which then displays the key-value pairs from the HashMap in an HTML table.


More Tags

printing-web-page spotfire json5 race-condition qunit uifont java-7 database-normalization bootstrap-datetimepicker nebular

More Java Questions

More Organic chemistry Calculators

More Other animals Calculators

More Biology Calculators

More Animal pregnancy Calculators