You define a listener class as an implementation of a listener interface. Table 4–2 lists the events that can be monitored and the corresponding interface that must be implemented. When a listener method is invoked, it is passed an event that contains information appropriate to the event. For example, the methods in the HttpSessionListener interface are passed an HttpSessionEvent, which contains an HttpSession.
Table 4–2 Servlet Life-Cycle Events
Object |
Event |
Listener Interface and Event Class |
---|---|---|
Web context (see Accessing the Web Context) |
Initialization and destruction | |
Attribute added, removed, or replaced | ||
Session (See Maintaining Client State) |
Creation, invalidation, activation, passivation, and timeout |
javax.servlet.http.HttpSessionListener, javax.servlet.http.HttpSessionActivationListener, and |
Attribute added, removed, or replaced | ||
Request |
A servlet request has started being processed by web components | |
Attribute added, removed, or replaced |
The tut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/listeners/ContextListener class creates and removes the database access and counter objects used in the Duke’s Bookstore application. The methods retrieve the web context object from ServletContextEvent and then store (and remove) the objects as servlet context attributes.
import database.BookDBAO; import javax.servlet.*; import util.Counter; import javax.ejb.*; import javax.persistence.*; public final class ContextListener implements ServletContextListener { private ServletContext context = null; @PersistenceUnit EntityManagerFactory emf; public void contextInitialized(ServletContextEvent event) { context = event.getServletContext(); try { BookDBAO bookDB = new BookDBAO(emf); context.setAttribute("bookDB", bookDB); } catch (Exception ex) { System.out.println( "Couldn’t create database: " + ex.getMessage()); } Counter counter = new Counter(); context.setAttribute("hitCounter", counter); counter = new Counter(); context.setAttribute("orderCounter", counter); } public void contextDestroyed(ServletContextEvent event) { context = event.getServletContext(); BookDBAO bookDB = context.getAttribute("bookDB"); bookDB.remove(); context.removeAttribute("bookDB"); context.removeAttribute("hitCounter"); context.removeAttribute("orderCounter"); } }