Traversing a HashMap in JSP is similar to doing so in plain Java code. Utilize the following loop structure:
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">String key = entry.getKey(); String value = entry.getValue(); // ...
}
While scriptlets were previously common, they are now regarded as poor practice. Instead, we recommend using JSTL, which provides the
<p><c:forEach items="${map}" var="entry"></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">Key = ${entry.key}, value = ${entry.value}<br>
To resolve your specific problem:
<p><select name="country"></p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><c:forEach items="${countries}" var="country"> <option value="${country.key}">${country.value}</option> </c:forEach>
To make ${countries} accessible in the requested scope, use a Servlet or ServletContextListener.
Here are examples of using Servlet or ServletContextListener:
<pre class="brush:php;toolbar:false">Map<String, String> countries = MainUtils.getCountries(); request.setAttribute("countries", countries); request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);</p> <p>}<br>
Or:
<pre class="brush:php;toolbar:false">Map<String, String> countries = MainUtils.getCountries(); event.getServletContext().setAttribute("countries", countries);</p> <p>}<br>
The above is the detailed content of How to Iterate Through HashMaps in JSP Using JSTL and Avoid Scriptlets?. For more information, please follow other related articles on the PHP Chinese website!