AddressBook/src/ContextListener.java

Notes

Purpose
The purpose of the AddressBook.ContextListener Java class is to create an instance of AddressBook.AddressDB and store it as an attribute in the servlet context identified as: "addressesDB". This will allow AddressBook's JSPs to retrieve the instance of AddressBook.AddressDB and access the Addresses table.

AddressBook.ContextListener is configured as a servlet context listener in the web.xml file.

contextInitialized
contextInitialized is called whenever the AddressBook web application is starting up.

First the servlet context is retrieved from the servlet context event:

    ServletContext servletContext = servletContextEvent.getServletContext ();

Then an AddressesDB instance is created and saved in the servlet context identified as: "addressesDB". If an exception is thrown by this process, an error message is logged:

    try
    {
        AddressesDB addressesDB = new AddressesDB ();
        servletContext.setAttribute ("addressesDB", addressesDB);
    }
    catch (Exception e)
    {
        servletContext.log ("Couldn't create addressesDB sttribute: " + e.getMessage());
    }

contextDestroyed
contextDestroyed is called whenever the AddressBook web application is shutting down.

First the servlet context is retrieved from the servlet context event:

    ServletContext servletContext = servletContextEvent.getServletContext ();

Then the AddressesDB is retrieved from the servlet context and the database is closed:

    AddressesDB addressesDB = (AddressesDB) servletContext.getAttribute ("addressesDB");
    addressesDB.close ();

Then the attribute is removed from the servlets context:

    servletContext.removeAttribute ("addressesDB"); 

Complete Source Code


//
//  ContextListener.java
//

package AddressBook;

import javax.servlet.*;

public final class ContextListener
implements ServletContextListener
{
    public void contextInitialized (ServletContextEvent servletContextEvent)
    {
        ServletContext servletContext = servletContextEvent.getServletContext ();
        try
        {
            AddressesDB addressesDB = new AddressesDB ();
            servletContext.setAttribute ("addressesDB", addressesDB);
        }
        catch (Exception e)
        {
            servletContext.log ("Couldn't create addressesDB sttribute: " + e.getMessage ());
        }
    }

    public void contextDestroyed (ServletContextEvent servletContextEvent)
    {
        ServletContext servletContext = servletContextEvent.getServletContext ();
        AddressesDB addressesDB = (AddressesDB) servletContext.getAttribute ("addressesDB");
        addressesDB.close ();
        servletContext.removeAttribute ("addressesDB");
    }

}