How to effectively iterate through a HashMap within JSP scriptlets to populate a drop-down list?
In JSP, traversing a HashMap is identical to regular Java code. One can employ the following approach:
for (Map.Entry<String, String> entry : countries.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); }
However, using JSP scriptlets is discouraged. Instead, it's recommended to leverage JSTL's
For instance:
<%@ taglib prefix="c" uri="jakarta.tags.core" %> <c:forEach items="${map}" var="entry"> Key = ${entry.key}, value = ${entry.value}<br> </c:forEach>
Adapting the aforementioned code to populate a drop-down list:
<%@ 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 make countries accessible from within ${countries}, it needs to be placed in the appropriate scope. This can be achieved through:
Request scope (Servlet doGet method):
protected void doGet(HttpServletRequest request, HttpServletResponse response) { Map<String, String> countries = MainUtils.getCountries(); request.setAttribute("countries", countries); request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response); }
Application-wide scope (ServletContextListener contextInitialized method):
public void contextInitialized(ServletContextEvent event) { Map<String, String> countries = MainUtils.getCountries(); event.getServletContext().setAttribute("countries", countries); }
The above is the detailed content of How to Iterate Through a HashMap to Populate a JSP Dropdown List?. For more information, please follow other related articles on the PHP Chinese website!