如何在 JSP 中遍历 HashMap
?
<%
HashMap<String, String> countries = MainUtils.getCountries(l);
%>
<select name="country">
<%
// Here I need to loop through countries.
%>
</select>
就像在普通的Java代码中一样。
for (Map.Entry<String, String> entry : countries.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}
<% %>
的东西)被认为是一种不良实践。我建议安装JSTL(只需将JAR文件放入/ WEB-INF / lib
并在JSP顶部声明所需的taglibs即可)。它有一个<c:forEach>
标签,可以循环遍历其他 Map
。每次迭代都会返回一个 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>
<%@ 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()
: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()
方法,以便它只会被加载一次并保存在内存中:public void contextInitialized(ServletContextEvent event) {
Map<String, String> countries = MainUtils.getCountries();
event.getServletContext().setAttribute("countries", countries);
}
countries
将通过${countries}
在EL中可用。countries.keySet()
:遍历键countries.entrySet()
:遍历键值对countries.values()
:遍历值以下代码对我有效:
首先在服务器端定义了如下的partnerTypesMap
:
Map<String, String> partnerTypes = new HashMap<>();
在给它添加值后,我将对象添加到model
中。
model.addAttribute("partnerTypesMap", partnerTypes);
foreach
来逐个打印它们。<c:forEach items="${partnerTypesMap}" var="partnerTypesMap">
<form:option value="${partnerTypesMap['value']}">${partnerTypesMap['key']}</form:option>
</c:forEach>
HashMap
本质上是无序的。你确定不需要TreeMap
(键排序)或者LinkedHashMap
(维护插入顺序)吗? - BalusC