Assuming that you want to load this HashMap only for one web application you can do it when container loads all settings for your app (after it reads web.xml
file). To do this you can create class which implements ServletContextListener
.
In its contextInitialized
method create HashMap you are interested in, and add it as attribute to ServletContext
. There can be only one ServletContext
instance for one web application and this instance is available to all servlets/jsp so they can later get that attribute with map you set earlier.
Example:
class ContextListenerImpl implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sce) {
//can be empty for now
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
//... here you can create and initialize your HashMap
//when map is ready add it as attribute to servlet context
sc.setAttribute("mySpecialMap", map);
}
}
You can get this map in servlets like
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//...
Map<Your,Types> map = (Map<Your,Types>) getServletContext()
.getAttribute("mySpecialMap");
//...
}
Oh, and one important thing: lets not forget to add this listener to your web application. So you will have to add
<listener>
<listener-class>full.name.of.ContextListenerImpl</listener-class>
</listener>
to your web.xml
file.