tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Craig R. McClanahan" <>
Subject Re: API 2.3: Listener vs. load-on-startup
Date Fri, 09 Nov 2001 16:46:49 GMT

On 9 Nov 2001, Dr. Evil wrote:

> Date: 9 Nov 2001 07:43:17 -0000
> From: Dr. Evil <>
> Reply-To: Tomcat Users List <>
> To:
> Subject: API 2.3: Listener vs. load-on-startup
> I have a few classes that need to be loaded by Tomcat before it starts
> to serve any requests.  One of these opens a database pool, another
> opens a logger, etc.  The traditional way to do this is with
> load-on-startup like this:
>    <servlet>
>       <servlet-name>startlogging</servlet-name>
>       <servlet-class>startlogging</servlet-class>
>       <load-on-startup>1</load-on-startup>
>    </servlet>
> which calls the init() method of the class.
> However, I need to have an object installed into the ServletContext
> object before any requests can be serviced.  The init() method of a
> servlet seems to have no access to the ServletContext object (is this
> correct?).

You have access to the servlet context via the getServletContext() method
of the servlet -- it is pre-initialized to work for you.  However, using a
listener is the better way to do this in a Servlet 2.3 environment.

>  Because of this, I am thinking of using the new <listener>
> declaration to achieve this same goal.  I can declare a listener like
> this:
> <listener>
> 	<listener-class>dostartupstuff</listener-class>
> </listener>
> and then in the dostartupstuff class, I declare a method:
> public void contexInitialized(ServletContextEvent e) { ... }
> which will be called as soon as the context is created.
> Is this the right way to do this?

Yes.  That is exactly what context listeners are designed to do.

Why is it better than a servlet init() method?  Because the container
gives you *no* guarantee that it will keep a servlet loaded for the
lifetime of the application (although many of them do), so if you clean up
your resources in the destroy() method -- such as closing database
connections -- this might happen to you at a bad time.  The
contextDestroyed() method of your listener will not get called until the
application is really being shut down.

> And is there a way I can control
> the order in which listeners are called?

At startup time, listeners are called in the order they are defined in the
deployment descriptor -- at shutdown time, they are called in reverse
order.  For more info, see the 2.3 spec:

> Thanks


To unsubscribe:   <>
For additional commands: <>
Troubles with the list: <>

View raw message