views:

1664

answers:

2

Hello,

the related Questions couldn't help me very much. How can i loop through a HashMap in jsp like this example:

<%
    HashMap<String, String> countries = MainUtils.getCountries(l);
%>

<select name="ccountry" id="ccountry" >
            <% //HERE I NEED THE LOOP %>           
</select>*<br/>
A: 

Iterate over countries.keySet(), countries.entrySet() or countries.values() instead, depending on what you want to accomplish within the loop.

Jim Garrison
yes,with this i get alle key set but how can i integrate it into a select field for html?
blub
+12  A: 

Scriptlets (raw Java code in JSP files, between <% and %> things) are considered bad practice. I recommend to install JSTL (just place the JAR file in /WEB-INF/lib and declare the needed taglibs in top of JSP). It has a c:forEach tag which can iterate over under each Maps. Every iteration will give you a Map.Entry which on its turn has getKey() and getValue() methods.

Here's a basic example:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:forEach items="${map}" var="entry">
    Key = ${entry.key}, value = ${entry.value}<br>
<c:forEach>

Thus your particular issue can be solved as follows:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<select name="country">
    <c:forEach items="${countries}" var="country">
        <option value="${country.key}">${country.value}</option>
    <c:forEach>
</select>

You need a Servlet or a ServletContextListener to place the ${countries} in the desired scope. If this list is supposed to be request-based, then use the Servlet's doGet():

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);
}

Or if this list is supposed to be an application-wide constant, then use ServletContextListener's contextInitialized() so that it will be loaded only once and kept in memory:

public void contextInitialized(ServletContextEvent event) {
    Map<String, String> countries = MainUtils.getCountries();
    event.getServletContext().setAttribute("countries", countries);
}

In both cases the countries will be available in EL by ${countries}.

Hope this helps.

BalusC
Very detailed explanation.
ChadNC