Servlet that will be called each time when server starts

Discussions

Web tier: servlets, JSP, Web frameworks: Servlet that will be called each time when server starts

  1. Hi,

    how can I make servlet that will be called each time when server starts - I need to do some initialization at each start-up.
  2. I think this is what you're looking for. The code in init will only be called once, upon loading the servlet.


    public class SomeServlet extends javax.servlet.http.HttpServlet
    {

      /**
       * Initializes the servlet.
       */
      public void init()
      {
      }

      ... blah blah blah ...
    }
  3. Most of J2EEe servers today have startup and shutdown classes: their code will be executed on appropriate event. This is however not a part of J2EE standard: you'll have to browse your server's documentation
  4. Hi Saruman,

    may I ask you to give me an example from any J2EE server - I hope that all vendors go similar ways.

    Thanks
  5. There is a "load-on-startup" element in the servlet deployment descriptor that can be used to load the servlet when the web application starts. You can put your initialization code in the servlet's init() method.

    Example:

    <web-app>
        <servlet>
            <servlet-name>startup</servlet-name>
    <servlet-class>com.myhost.servlet.StartupServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
        </servlet>
    </web-app>