I build a web application with JSPs and in my servlet I have:
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletReque
In my point of view, a good way is to implement a Servlet Context Listener. It listens to application startup and shutdown.
public class YourListener implements javax.servlet.ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
And then, you configure the listener in your web.xml () or with the @WebServletContextListener annotation.
You can configure it in Tomcat's web.xml (or corresponding configuration files in similar servers), like below using the tag <load-on-startup>
:
<servlet>
<servlet-name>MyOwnServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Whatever you want done on startup should be done by a class implementing ServletContextListener
, so you should write such a class, for example:
public class MyContextListener
implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
//do stuff
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
//do stuff before web application is started
}
}
Then you should declare it in web.xml:
<listener>
<listener-class>
com.whatever.MyContextListener
</listener-class>
</listener>