JSP で HashMap をループするにはどうすればいいですか? 質問する

JSP で HashMap をループするにはどうすればいいですか? 質問する

JSP でループするにはどうすればよいでしょうかHashMap?

<%
    HashMap<String, String> countries = MainUtils.getCountries(l);
%>

<select name="country">
    <% 
        // Here I need to loop through countries.
    %>
</select>

ベストアンサー1

通常の Java コードで行うのと同じ方法です。

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

しかしスクリプトレット(JSPファイル内の生のJavaコードなど<% %>)は、悪い習慣インストールすることをお勧めしますJSTL. それは<c:forEach>他のタグを反復処理できるタグMap。反復処理ごとにMap.Entryバックには、メソッドgetKey()getValue()メソッドがあります。

基本的な例を以下に示します。

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<c:forEach items="${map}" var="entry">
    Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>

したがって、特定の問題は次のように解決できます。

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<select name="country">
    <c:forEach items="${countries}" var="country">
        <option value="${country.key}">${country.value}</option>
    </c:forEach>
</select>

を目的のスコープ内に配置するには、Servletまたは が必要です。このリストがリクエストベースである場合は、の を使用します。ServletContextListener${countries}ServletdoGet()

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

または、このリストがアプリケーション全体の定数である場合は、 を使用して、リストが 1 回だけ読み込まれ、メモリ内に保持されるようにしますServletContextListenercontextInitialized()

public void contextInitialized(ServletContextEvent event) {
    Map<String, String> countries = MainUtils.getCountries();
    event.getServletContext().setAttribute("countries", countries);
}

どちらの場合もcountriesエルによる${countries}

参照:

おすすめ記事