且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 JSP 中循环遍历 HashMap?

更新时间:2023-11-03 09:16:22

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

Just the same way as you would do in normal Java code.

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


然而scriptlets(JSP文件中的原始Java代码,那些东西)被认为是糟糕的做法.我建议安装 JSTL(只需删除 JAR 文件在 /WEB-INF/lib 并声明所需的 taglibs 在 JSP 之上).它有一个 ; 标签,它可以在其他Maps 中迭代.每次迭代都会给你一个 Map.入口返回,依次有getKey()getValue()方法.


However, scriptlets (raw Java code in JSP files, those <% %> things) are considered a poor practice. I recommend to install JSTL (just drop 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 among others Maps. Every iteration will give you a Map.Entry back which in turn has getKey() and getValue() methods.

这是一个基本示例:

<%@ 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>

您需要一个 Servlet 或一个 ServletContextListener 来将 ${countries} 放置在所需的范围内.如果这个列表应该是基于请求的,那么使用 ServletdoGet():

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

或者如果这个列表应该是一个应用程序范围的常量,那么使用 ServletContextListenercontextInitialized() 这样它只会被加载一次并保存在记忆:

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

在这两种情况下,countries 将在 ${countries} 的noreferrer">EL.

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

希望这会有所帮助.