yaylitzis
yaylitzis

Reputation: 5554

Execute servlet on startup of the application

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?

Upvotes: 4

Views: 5685

Answers (3)

NickJ
NickJ

Reputation: 9579

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>

Upvotes: 8

vincent
vincent

Reputation: 1244

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.

Upvotes: 2

Dimos
Dimos

Reputation: 8928

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>

Upvotes: 4

Related Questions