Making a Connection Pool Available to Application Components

The next part of the puzzle is how to make the DataSource available to the application components that need it. In principle, there are two ways to do this. The first one -- using an application scope variable -- works in any type of web container, while the second one -- using JNDI -- is more flexible but only works in a container that supports J2EE style resource access.

Using an Application Scope Variable

One place for resources that all components in an application need access to is the application scope, corresponding to ServletContext attributes in the servlet world. As I described in Chapter 18, the most appropriate component for initialization and release of this type of shared resources is the application lifecycle listener. In a web container that doesn’t implement the Servlet 2.3 API yet, a servlet that’s loaded at startup can perform the same duties, but it’s not a perfect fit.[18]

The container informs an application lifecycle listener when the application is started and stopped. It can create the resource objects and make them available to other application components in its contextInitialized( ) method before any user requests are received, and release them when the application is shut down in its contextDestroyed( ) method. Finally, a listener can use configuration data (defined as context parameters in the deployment descriptor) to work in different settings. To recap, here’s an application lifecycle ...

Get JavaServer Pages, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.