如何在JSP中循环HashMap?

blu*_*lub 140 java jsp loops hashmap

如何HashMap在JSP中循环?

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

<select name="country">
    <% 
        // Here I need to loop through countries.
    %>
</select>
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 299

就像在普通Java代码中一样.

for (Map.Entry<String, String> entry : countries.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    // ...
}
Run Code Online (Sandbox Code Playgroud)

但是,scriptlet(JSP文件中的原始Java代码,这些<% %>东西)被认为是一种不好的做法.我建议安装JSTL(只需删除JAR文件/WEB-INF/lib并在JSP顶部声明所需的taglib).它有一个<c:forEach>标签,可以迭代其他Maps.每次迭代会给你Map.Entry回这反过来又getKey()getValue()方法.

这是一个基本的例子:

<%@ 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>
Run Code Online (Sandbox Code Playgroud)

因此,您的特定问题可以解决如下:

<%@ 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>
Run Code Online (Sandbox Code Playgroud)

您需要a Servlet或a ServletContextListener将其${countries}置于所需范围内.如果这个列表应该是基于请求的,那么使用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);
}
Run Code Online (Sandbox Code Playgroud)

或者如果这个列表应该是一个应用程序范围的常量,那么使用ServletContextListener's' contextInitialized()使它只加载一次并保存在内存中:

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

在这两种情况下,countries将在EL通过${countries}.

希望这可以帮助.

也可以看看:

  • @Khue:是的,你也可以在会话中放置属性.我只是不明白为什么你想在多个会话上复制应用程序范围的数据. (2认同)