Initializing Shared Resources Using a Listener

The Project Billboard application uses two business logic beans that must be available to process requests from all users; in other words, available as application scope objects. You may remember the NewsBean from Chapter 12. This bean is the repository for all news items relating to projects, used as the source for the personalized message list. The other business logic bean is called EmployeeRegistryBean. It acts as an abstraction of the database with employee information containing methods for user authentication and retrieving and saving employee information. The EmployeeRegistryBean class is described in more detail in Chapter 19.

Beans like this typically need to be initialized before they can be used. For instance, they may need a reference to a database or some other external data source and may create an initial information cache in memory to provide fast access even to the first request for data. You can include code for initialization of the shared resources in the servlet and JSP pages that need them, but a more modular approach is to place all this code in one place and let the other parts of the application work on the assumption that the resources are already initialized and available. An application lifecycle listener is a perfect tool for this type of resource initialization. Example 18-5 shows a listener suitable for the billboard application’s needs. This type of listener implements the javax.servlet.ServletContextListener ...

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.