如何在 JSP scriptlet 中有效地迭代 HashMap 来填充下拉列表?
在JSP中,遍历 HashMap 与常规 Java 代码相同。可以采用以下方法:
for (Map.Entry<string string> entry : countries.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); }</string>
但是,不鼓励使用 JSP scriptlet。相反,建议利用 JSTL 的
例如:
<foreach items="${map}" var="entry"> Key = ${entry.key}, value = ${entry.value}<br> </foreach>
调整上述代码用于填充下拉列表:
<select name="country"> <foreach items="${countries}" var="country"> <option value="${country.key}">${country.value}</option> </foreach> </select>
要使${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); }</string>
应用程序范围(ServletContextListener contextInitialized方法):
public void contextInitialized(ServletContextEvent event) { Map<string string> countries = MainUtils.getCountries(); event.getServletContext().setAttribute("countries", countries); }</string>
以上是如何迭代 HashMap 来填充 JSP 下拉列表?的详细内容。更多信息请关注PHP中文网其他相关文章!