How to Loop Through a HashMap in JSP
Wanting to loop through a HashMap in JSP? It's easy, following the same principles as you would in normal Java code:
for (Map.Entry<String, String> entry : countries.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); // ... }
However, using scriptlets (raw Java code in JSP files) is considered poor practice. Instead, consider installing JSTL. Its
Here's a basic JSTL example:
<%@ taglib prefix="c" uri="jakarta.tags.core" %> <c:forEach items="${map}" var="entry"> Key = ${entry.key}, value = ${entry.value}<br> </c:forEach>
Applying this to your specific case, you could solve it with:
<%@ taglib prefix="c" uri="jakarta.tags.core" %> <select name="country"> <c:forEach items="${countries}" var="country"> <option value="${country.key}">${country.value}</option> </c:forEach> </select>
To use ${countries} in EL, you'll need a Servlet or ServletContextListener to place it in the desired scope. For request-based scenarios, use the Servlet's doGet(). For application-wide constants, employ ServletContextListener's contextInitialized().
For further insights, check out these resources:
The above is the detailed content of How to Iterate Through a HashMap in JSP Using JSTL?. For more information, please follow other related articles on the PHP Chinese website!