Next to JSP there's also the Servlet API.
If the map is request or session specific, then create a class which extends HttpServlet
and implement doGet()
method like follows:
Map<K, V> map = createItSomehow();
request.setAttribute("map", map);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
Register the Servlet
in web.xml
on a certain url-pattern
and invoke an URL matching this pattern.
This way the map
is available as ${map}
in JSP. Here's an example which iterates over the map
using JSTL c:forEach
tag:
<c:forEach items="${map}" var="entry">
Key: ${entry.key}, Value: ${entry.value}<br>
</c:forEach>
If the map is an application wide constant, then rather implement ServletContextListener
and do the following in contextInitialized()
method:
Map<K, V> map = createItSomehow();
event.getServletContext().setAttribute("map", map);
Register the ServletContextListener
in web.xml
as follows:
<listener>
<listener-class>com.example.Config</listener-class>
</listener>
and it will be executed on webapp's startup. The map
is then available in JSP by ${map}
as well.
See also: