Question

I'm working on some Java EE application which has to find some data in HashMap. The problem is that I want to load this HashMap to Tomcat only once - when Tomcat starts and I don't know how to do this. Could you give me some tips?

Was it helpful?

Solution 2

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.

OTHER TIPS

I suppose you want to load HashMap actually before when your web application start.

The ServletContextListener is what you want. It will make your code run before the web application is start.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top