I build a web application with JSPs and in my servlet I have:
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
init();
HttpSession session = request.getSession(true);
//more code...
}
}
Till now my serlvet is called, when the JSP page calls it like <a href="MyServlet..">
. What I want is whenever the application starts, the servlet to be executed as well. I could have a button in my 1st page like "START" and there to call the servlet.. But, can I avoid this?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With