Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute servlet on startup of the application

Tags:

java

servlets

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?

like image 431
yaylitzis Avatar asked Dec 15 '22 13:12

yaylitzis


2 Answers

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>
like image 67
NickJ Avatar answered Jan 01 '23 01:01

NickJ


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>
like image 39
Dimos Avatar answered Dec 31 '22 23:12

Dimos