就像使用普通Java代码一样。
for (Map.Entry<String, String> entry : countries.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); // ...}但是,
scriptlet(JSP文件中的原始Java代码,那些
<% %>东西)被认为是不明智的做法。我建议安装JSTL(只需将JAR文件放入其中,
/WEB-INF/lib并在JSP顶部声明所需的taglib)。它有一
个<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都可以在EL中使用
${countries}。希望这可以帮助。



