Discussions

Web tier: servlets, JSP, Web frameworks: Elegant way to do initialization in Tomcat

  1. Elegant way to do initialization in Tomcat (2 messages)

    I have to make some initialization stuff after launching
    Tomcat - opening database connection pool, starting
    threads updating some data periodically etc. I haven't found any nice way to do this - currently I just have to load some jsp page containing declarations of application-scope beans,
    but I think there should be some nicer way. Does anyone have some experience with things like that and wants to share knowledge?

    Thanks in advance,
    Lukasz Fryz

  2. I'd like to know, too! I've seen some container-specific things (i.e. WebLogic Server "startup classes",

    http://www.weblogic.com/docs45/classdocs/API_server.html#startup

    but I'd love some way that would work with any Servlet/JSP product (not using some vendor's intialization feature).

    I have seen people hack the startup scripts for various app servers... they'll start the server in the background (on unix), wait awhile, and then run a command-line web client and request a Servlet or JSP which does the initialization... you could do this in a few lines of Java code). But it's such a hack.

  3. One way to achieve this in Tomcat is to create a servlet with all of the initialization code in the init() method. Then, in your web.xml file, register the servlet:

    <servlet>
      <servlet-name>InitServlet</servlet-name>
      <servlet-class>my.package.InitServlet</servlet-class>
      <load-on-startup></load-on-startup>
    </servlet>

    You can specify a number after the <load-on-startup> to specify a load order, in case you've got multiple servlets loading on startup.

    I don't think this will work with WebLogic 5.1, as I remember reading in the developer guide that <load-on-startup> is not implemented in WebLogic. WebLogic does support startup classes, though, which are a WebLogic specific way to do initialization upon starting the app server.

    Hope this helps,

    Andy Nguyen