How to loop through a HashMap in JSP?

前端 未结 3 1252
长发绾君心
长发绾君心 2020-11-22 02:18

How can I loop through a HashMap in JSP?

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


    
        
    

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 countries = MainUtils.getCountries();
    request.setAttribute("countries", countries);
    request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}

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 countries = MainUtils.getCountries();
    event.getServletContext().setAttribute("countries", countries);
}

In both cases the countries will be available in EL by ${countries}.

Hope this helps.

See also:

  • Iterate over elements of List and Map using JSTL tag
  • How to iterate over a nested map in
  • How to iterate an ArrayList inside a HashMap using JSTL?
  • Using special auto start servlet to initialize on startup and share application data

提交回复
热议问题