-2

I want run a program on server startup of my web application wherein i need to read the data from the db and cache the data and use it across the application. Apart from the below approach is there any better solution to achieve the same

<servlet>
    <servlet-name>CacheData</servlet-name>
    <servlet-class>com.my.webapp.CacheDataServletExample</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

Since in the init method i need to invoke the db operations and cache it. Apart from that if any better solution is there please let me know.

Thanks in advance

nsarvesh
  • 37
  • 1
  • 2
  • 9
  • Possible duplicate of [Is there a way to run a method/class only on Tomcat/Wildfly/Glassfish startup?](https://stackoverflow.com/questions/158336/is-there-a-way-to-run-a-method-class-only-on-tomcat-wildfly-glassfish-startup) – Sundararaj Govindasamy Aug 14 '18 at 14:14

1 Answers1

0

you could register a context listener at startup in web.xml, like this:

<listener>
    <listener-class>it.example.WebAppServletContextListener</listener-class>
</listener>

and you can handle all your stuff in the listener implementation:

package it.example;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class WebAppServletContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // stuff to do on context destroy
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // stuff todo at context startup
    }
 }

P.S. since servlet 3.0 you can also use @WebListener annotation instead of declare listeners in web.xml

100ferhas
  • 61
  • 1
  • 3