Miles Daffin wrote:

> Craig,
>
> I was wondering if there is an optimal way of doing the following in TomCat?
> If you have the time to briefly describe such....
>
> Thanks
>
> Miles
>
> > > >(I prefer to store global application
> > > objects in
> > > > the servlet context, so that they are easily visible to all servlets
> and
> > > JSP
> > > > pages in my apps).
>
> p.s. please would you cc any response to my address.

Yes, it's easy in Tomcat (or any other servlet container that implements servlet
2.2 or later).

What I normally do is define a servlet to initialize my application resources,
and declare it <load-on-startup> in the web.xml file (so that the time-consuming
stuff happens when the server starts instead of on the first request).  As part
of the init() method of this servlet, I store these resources as a servlet
context attribute.

For example, lets say you have a nice fancy connection pool object that you want
to make available to the servlets and JSP pages of your application.  In the
init() method of the startup servlet, you just need to do the following:

    ConnectionPool myPool = ... create the pool object ...
    getServletContext().setAttribute("pool", myPool);

Now, any servlet in your application can acquire a reference to this pool in the
doGet() or doPost() method:

    ConnectionPool thePool =
      (ConnectionPool) getServletContext().getAttribute("pool");

Or, in a JSP page, you can access it like this:

    <jsp:useBean id="pool" type="com.mycompany.ConnectionPool"
     scope="application"/>

Craig McClanahan


Reply via email to