问题描述
如何在 JSP 中遍历 HashMap
?
How can I loop through a HashMap
in JSP?
<%
HashMap<String, String> countries = MainUtils.getCountries(l);
%>
<select name="country">
<%
// Here I need to loop through countries.
%>
</select>
推荐答案
就像在普通 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 之上).它有一个 ;
标签,它可以在其他Map
s 中迭代.每次迭代都会给你一个 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 Map
s. 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}
放置在所需的范围内.如果这个列表应该是基于请求的,那么使用 Servlet
的 doGet()
:
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);
}
或者如果这个列表应该是一个应用程序范围的常量,那么使用 ServletContextListener
的 contextInitialized()
这样它只会被加载一次并保存在记忆:
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}
.
希望这会有所帮助.
- 遍历 List 的元素并使用 JSTL 映射标签
- 如何迭代 < 中的嵌套地图c:forEach>
- 如何在 HashMap 中迭代 ArrayList使用 JSTL?
- 使用特殊的自动启动 servlet在启动时初始化并共享应用程序数据
这篇关于如何在 JSP 中循环遍历 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!