How to load once (when Tomcat starts) some data (HashMap) into the Tomcat cache?

I am working on some Java EE application that should find some data in a HashMap. The problem is that I want to load this HashMap into Tomcat only once - when Tomcat starts up, and I don't know how to do it. Could you give me some advice?

+4
source share
2 answers

Assuming that you want to download this HashMap for only one web application, you can do this when the container loads all the settings of your application (after reading the file web.xml). To do this, you can create a class that implements ServletContextListener.

contextInitialized HashMap ServletContext. - ServletContext, /jsp, .

:

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

,

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    //...
    Map<Your,Types> map = (Map<Your,Types>) getServletContext()
                                .getAttribute("mySpecialMap");
    //...
}

, : -.

<listener>
    <listener-class>full.name.of.ContextListenerImpl</listener-class>
</listener>

web.xml .

+1

, HashMap , -.

ServletContextListener - , . -.

+2

Source: https://habr.com/ru/post/1539418/


All Articles