Defining the Listener Class
You define a listener class as an implementation of a listener interface. Table 113 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.
|
Object |
Event |
Listener Interface and Event Class |
|
Web context (see Accessing the Web Context, page 473) |
Initialization and destruction |
javax.servlet. ServletContextListener and ServletContextEvent |
|
Attribute added, removed, or replaced |
javax.servlet. ServletContextAttributeListener and ServletContextAttributeEvent | |
|
Session (See Maintaining Client State, page 474) |
Creation, invalidation, activation, passivation, and timeout |
javax.servlet.http. HttpSessionListener, javax.servlet.http. HttpSessionActivationListener, and HttpSessionEvent |
|
Attribute added, removed, or replaced |
javax.servlet.http. HttpSessionAttributeListener and HttpSessionBindingEvent |
|
Object |
Event |
Listener Interface and Event Class |
|
Request |
A servlet request has started being processed by web components |
javax.servlet. ServletRequestListener and ServletRequestEvent |
|
Attribute added, removed, or replaced |
javax.servlet. ServletRequestAttributeListener and ServletRequestAttributeEvent |
The 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;
public final class ContextListener implements ServletContextListener { private ServletContext context = null;
public void contextInitia1ized(Serv1etContextEvent event) { context = event.getServ1etContext(); try {
BookDBAO bookDB = new BookDBAO(); context.setAttribute("bookDB", bookDB); } catch (Exception ex) { System.out.print1n(
"Couldn't create database: " + ex.getMessage());
Counter counter = new Counter(); context.setAttribute("hitCounter", counter); counter = new Counter();
context.setAttribute("orderCounter", counter);
public void contextDestroyed(Serv1etContextEvent event) { context = event.getServ1etContext(); BookDBAO bookDB = context.getAttribute("bookDB"); bookDB.remove();
- removeAttribute("bookDB");
- removeAttribute("hitCounter"); context.removeAttribute("orderCounter");
Post a comment