Servlet Listener

来源:互联网 发布:json encode 不转义 编辑:程序博客网 时间:2024/05/18 06:02

The servlet specification includes the capability to track key events in your Web applications through event listeners. This functionality allows more efficient resource management and automated processing based on event status. The following sections describe servlet event listeners:

  • Event Categories and Listener Interfaces

  • Typical Event Listener Scenario

  • Event Listener Declaration and Invocation

  • Event Listener Coding and Deployment Guidelines

  • Event Listener Methods and Related Classes

  • Event Listener Sample

Event Categories and Listener Interfaces

There are two levels of servlet events:

  • Servlet context-level (application-level) event

    This event involves resources or state held at the level of the application servlet context object.

  • Session-level event

    This event involves resources or state associated with the series of requests from a single user session; that is, associated with the HTTP session object.

Each of these two levels has two event categories:

  • Lifecycle changes

  • Attribute changes

You can create one or more event listener classes for each of the four event categories. A single listener class can monitor multiple event categories.

Create an event listener class by implementing the appropriate interface or interfaces of the javax.servlet package or javax.servlet.http package. Table 3-1 summarizes the four categories and the associated interfaces.

Table 3-1 Event Listener Categories and Interfaces

Event Category Event Descriptions Java Interface

Servlet context lifecycle changes

Servlet context creation, at which point the first request can be serviced

Imminent shutdown of the servlet context

javax.servlet. ServletContextListener

Servlet context attribute changes

Addition of servlet context attributes

Removal of servlet context attributes

Replacement of servlet context attributes

javax.servlet. ServletContextAttributeListener

Session lifecycle changes

Session creation

Session invalidation

Session timeout

javax.servlet.http. HttpSessionListener

Session attribute changes

Addition of session attributes

Removal of session attributes

Replacement of session attributes

javax.servlet.http. HttpSessionAttributeListener


Typical Event Listener Scenario

Consider a Web application comprising servlets that access a database. A typical use of the event listener mechanism would be to create a servlet context lifecycle event listener to manage the database connection. This listener may function as follows:

  1. The listener is notified of application startup.

  2. The application logs in to the database and stores the connection object in the servlet context.

  3. Servlets use the database connection to perform SQL operations.

  4. The listener is notified of imminent application shutdown (shutdown of the Web server or removal of the application from the Web server).

  5. Prior to application shutdown, the listener closes the database connection.

Event Listener Declaration and Invocation

Event listeners are declared in the application web.xml deployment descriptor through <listener> elements under the top-level <web-app> element. Each listener has its own <listener> element, with a <listener-class> subelement specifying the class name. Within each event category, event listeners should be specified in the order in which you would like them to be invoked when the application runs.

After the application starts up and before it services the first request, the servlet container creates and registers an instance of each listener class that you have declared. For each event category, listeners are registered in the order in which they are declared. Then, as the application runs, event listeners for each category are invoked in the order of their registration. All listeners remain active until after the last request is serviced for the application.

Upon application shutdown, session event listeners are notified first, in reverse order of their declarations, then application event listeners are notified, in reverse order of their declarations.

Here is an example of event listener declarations, from the Sun Microsystems Java Servlet Specification, Version 2.3:

<web-app>   <display-name>MyListeningApplication</display-name>   <listener>      <listener-class>com.acme.MyConnectionManager</listenerclass>   </listener>   <listener>      <listener-class>com.acme.MyLoggingModule</listener-class>   </listener>   <servlet>      <display-name>RegistrationServlet</display-name>      ...   </servlet></web-app>

Assume that MyConnectionManager and MyLoggingModule both implement the ServletContextListener interface, and that MyLoggingModule also implements the HttpSessionListener interface.

When the application runs, both listeners are notified of servlet context lifecycle events, and the MyLoggingModule listener is also notified of session lifecycle events. For servlet context lifecycle events, the MyConnectionManager listener is notified first, because of the declaration order.

Event Listener Coding and Deployment Guidelines

Be aware of the following rules and guidelines for event listener classes:

  • In a multithreaded application, attribute changes may occur simultaneously. There is no requirement for the servlet container to synchronize the resulting notifications; the listener classes themselves are responsible for maintaining data integrity in such a situation.

  • Each listener class must have a public zero-argument constructor.

  • Each listener class file must be packaged in the application WAR file, either under /WEB-INF/classes or in a JAR file in /WEB-INF/lib.


    Note:

    In a distributed environment, the scope of event listeners is one for each deployment descriptor declaration for each JVM. There is no requirement for distributed Web containers to propagate servlet context events or session events to additional JVMs. The servlet specification discusses this.

Event Listener Methods and Related Classes

This section contains event listener methods that are called by the servlet container when a servlet context event or session event occurs. These methods take different types of event objects as input, so these event classes and their methods are also discussed.

ServletContextListener Methods, ServletContextEvent Class

The ServletContextListener interface specifies the following methods:

  • void contextInitialized(ServletContextEvent sce)

    The servlet container calls this method to notify the listener that the servlet context has been created and the application is ready to process requests.

  • void contextDestroyed(ServletContextEvent sce)

    The servlet container calls this method to notify the listener that the application is about to be shut down.

The servlet container creates a javax.servlet.ServletContextEvent object that is input for calls to ServletContextListener methods. The ServletContextEvent class includes the following method, which your listener can call:

  • ServletContext getServletContext()

    Use this method to retrieve the servlet context object that was created or is about to be destroyed, from which you can obtain information as desired. See "Introduction to Servlet Contexts" for information about the javax.servlet.ServletContext interface.

ServletContextAttributeListener Methods, ServletContextAttributeEvent Class

The ServletContextAttributeListener interface specifies the following methods:

  • void attributeAdded(ServletContextAttributeEvent scae)

    The servlet container calls this method to notify the listener that an attribute was added to the servlet context.

  • void attributeRemoved(ServletContextAttributeEvent scae)

    The servlet container calls this method to notify the listener that an attribute was removed from the servlet context.

  • void attributeReplaced(ServletContextAttributeEvent scae)

    The servlet container calls this method to notify the listener that an attribute was replaced in the servlet context.

The container creates a javax.servlet.ServletContextAttributeEvent object that is input for calls to ServletContextAttributeListener methods. The ServletContextAttributeEvent class includes the following methods, which your listener can call:

  • String getName()

    Use method this to get the name of the attribute that was added, removed, or replaced.

  • Object getValue()

    Use this method to get the value of the attribute that was added, removed, or replaced. In the case of an attribute that was replaced, this method returns the old value, not the new value.

HttpSessionListener Methods, HttpSessionEvent Class

The HttpSessionListener interface specifies the following methods:

  • void sessionCreated(HttpSessionEvent hse)

    The servlet container calls this method to notify the listener that a session was created.

  • void sessionDestroyed(HttpSessionEvent hse)

    The servlet container calls this method to notify the listener that a session was destroyed.

The container creates a javax.servlet.http.HttpSessionEvent object that is input for calls to HttpSessionListener methods. The HttpSessionEvent class includes the following method, which your listener can call:

  • HttpSession getSession()

    Use this method to retrieve the session object that was created or destroyed, from which you can obtain information as desired. See "Introduction to Servlet Sessions" for information about the javax.servlet.http.HttpSession interface.

HttpSessionAttributeListener Methods, HttpSessionBindingEvent Class

The HttpSessionAttributeListener interface specifies the following methods:

  • void attributeAdded(HttpSessionBindingEvent hsbe)

    The servlet container calls this method to notify the listener that an attribute was added to the session.

  • void attributeRemoved(HttpSessionBindingEvent hsbe)

    The servlet container calls this method to notify the listener that an attribute was removed from the session.

  • void attributeReplaced(HttpSessionBindingEvent hsbe)

    The servlet container calls this method to notify the listener that an attribute was replaced in the session.

The container creates a javax.servlet.http.HttpSessionBindingEvent object that is input for calls to HttpSessionAttributeListener methods. The HttpSessionBindingEvent class includes the following methods, which your listener can call:

  • String getName()

    Use this method to get the name of the attribute that was added, removed, or replaced.

  • Object getValue()

    Use this method to get the value of the attribute that was added, removed, or replaced. In the case of an attribute that was replaced, this method returns the old value, not the new value.

  • HttpSession getSession()

    Use this method to retrieve the session object that had the attribute change.

Event Listener Sample

This section provides code for a sample that uses a servlet context lifecycle and session lifecycle event listener. This includes the following components:

  • SessionLifeCycleEventExample: This is the event listener class, implementing the ServletContextListener and HttpSessionListener interfaces.

  • SessionCreateServlet: This servlet creates an HTTP session.

  • SessionDestroyServlet: This servlet destroys an HTTP session.

  • index.jsp: This is the application welcome page (the user interface), from which you can invoke SessionCreateServlet or SessionDestroyServlet.

  • web.xml: This is the deployment descriptor, in which the servlets and listener class are declared.

To download and run this application, refer to the Use Servlet Lifecycle Events example at the following link:

http://www.oracle.com/technology/tech/java/oc4j/htdocs/oc4j-how-to.html

(These examples were written for older versions of OC4J, but the functionality is similar for the 10.1.2 implementation.)

You must be a member of the Oracle Technology Network, but memberships are free of charge.

Welcome Page: index.jsp

Here is the welcome page, the user interface that enables you to invoke the session-creation servlet by clicking the Create New Session link, or to invoke the session-destruction servlet by clicking the Destroy Current Session link.

<%@page session="false" %><H2>OC4J - HttpSession Event Listeners </H2><P>This example demonstrates the use of the HttpSession Event and Listener that isnew with the Java Servlet 2.3 API.  </P><P>[<a href="servlet/SessionCreateServlet">Create New Session</A>] &nbsp;[<a href="servlet/SessionDestroyServlet">Destroy Current Session</A>]</P><P>Click the Create link above to start a new HttpSession. An HttpSessionlistener has been configured for this application. The servler containerwill send an event to this listener when a new session is created or destroyed. The output from the event listener will be visible in the console window from where OC4J was started.</P>

Note:

No new session object is created if you click the Create New Session link again after having already created a session from the same client, unless the session has reached a timeout limit or you have explicitly destroyed it in the meantime.

Deployment Descriptor: web.xml

The servlets and the event listener are declared in the web.xml file. This results in SessionLifeCycleEventExample being instantiated and registered upon application startup. Because of this, the servlet container automatically calls its methods, as appropriate, upon the occurrence of servlet context or session lifecycle events. Here are the web.xml entries:

<web-app>   <listener>      <listener-class>SessionLifeCycleEventExample</listener-class>    </listener>   <servlet>      <servlet-name>sessioncreate</servlet-name>       <servlet-class>SessionCreateServlet</servlet-class>    </servlet>   <servlet>      <servlet-name>sessiondestroy</servlet-name>       <servlet-class>SessionDestroyServlet</servlet-class>    </servlet>   <welcome-file-list>      <welcome-file>index.jsp</welcome-file>    </welcome-file-list></web-app>

Listener Class: SessionLifeCycleEventExample

This section shows the listener class. Its sessionCreated() method is called by the servlet container when an HTTP session is created, which occurs when you click the Create New Session link in index.jsp. When sessionCreated() is called, it calls the log() method to print a "CREATE" message indicating the ID of the new session.

The sessionDestroyed() method is called when the HTTP session is destroyed, which occurs when you click the Destroy Current Session link. When sessionDestroyed() is called, it calls the log() method to print a "DESTROY" message indicating the ID and duration of the terminated session.

import javax.servlet.http.*;import javax.servlet.*;public class SessionLifeCycleEventExample    implements ServletContextListener, HttpSessionListener{   /* A listener class must have a zero-argument constructor: */   public SessionLifeCycleEventExample()   {   }   ServletContext servletContext;   /* Methods from the ServletContextListener */   public void contextInitialized(ServletContextEvent sce)   {      servletContext = sce.getServletContext();   }   public void contextDestroyed(ServletContextEvent sce)   {   }   /* Methods for the HttpSessionListener */   public void sessionCreated(HttpSessionEvent hse)   {      log("CREATE",hse);   }   public void sessionDestroyed(HttpSessionEvent hse)   {         HttpSession _session = hse.getSession();         long _start = _session.getCreationTime();         long _end = _session.getLastAccessedTime();         String _counter = (String)_session.getAttribute("counter");         log("DESTROY, Session Duration:"                    + (_end - _start) + "(ms) Counter:" + _counter, hse);   }      protected void log(String msg, HttpSessionEvent hse)   {      String _ID = hse.getSession().getId();      log("SessionID:" + _ID + "    " + msg);   }      protected void log(String msg)   {      System.out.println("[" + getClass().getName() + "] " + msg);   }}

Session Creation Servlet: SessionCreateServlet.java

This servlet is invoked when you click the Create New Session link in index.jsp. Its invocation results in the servlet container creating a request object and associated session object. Creation of the session object results in the servlet container calling the sessionCreated() method of the event listener class.

import java.io.*;import java.util.Enumeration;import java.util.Date;import javax.servlet.*;import javax.servlet.http.*;public class SessionCreateServlet extends HttpServlet {     public void doGet (HttpServletRequest req, HttpServletResponse res)      throws ServletException, IOException      {         //Get the session object         HttpSession session = req.getSession(true);                // set content type and other response header fields first        res.setContentType("text/html");        // then write the data of the response        PrintWriter out = res.getWriter();             String _sval = (String)session.getAttribute("counter");        int _counter=1;             if(_sval!=null)        {           _counter=Integer.parseInt(_sval);           _counter++;      }                session.setAttribute("counter",String.valueOf(_counter));      out.println("<HEAD><TITLE> " + "Session Created Successfully ..          Look at OC4J Console to see whether the HttpSessionEvent invoked "          + "</TITLE></HEAD><BODY>");      out.println("<P>[<A HREF=/"SessionCreateServlet/">Reload</A>]&nbsp;");         out.println("[<A HREF=/"SessionDestroyServlet/">Destroy Session</A>]");         out.println("<h2>Session created Successfully</h2>");      out.println("Look at the OC4J Console to see whether the HttpSessionEvent                  was invoked");      out.println("<h3>Session Data:</h3>");      out.println("New Session: " + session.isNew());      out.println("<br>Session ID: " + session.getId());      out.println("<br>Creation Time: " + new Date(session.getCreationTime()));      out.println("<br>Last Accessed Time: " +                    new Date(session.getLastAccessedTime()));      out.println("<BR>Number of Accesses: " + session.getAttribute("counter"));         }}

Session Destruction Servlet: SessionDestroyServlet.java

This servlet is invoked when you click the Destroy Current Session link in index.jsp. Its invocation results in a call to the invalidate() method of the session object. This, in turn, results in the servlet container calling the sessionDestroyed() method of the event listener class.

import java.io.*;import java.util.Enumeration;import javax.servlet.*;import javax.servlet.http.*;public class SessionDestroyServlet extends HttpServlet {     public void doGet (HttpServletRequest req, HttpServletResponse res)      throws ServletException, IOException      {         //Get the session object         HttpSession session = req.getSession(true);         // Invalidate Session         session.invalidate();          // set content type and other response header fields first         res.setContentType("text/html");         // then write the data of the response         PrintWriter out = res.getWriter();         out.println("<HEAD><TITLE> " + "Session Destroyed Successfully ..            Look at OC4J Console to see whether the HttpSessionEvent invoked "            + "</TITLE></HEAD><BODY>");         out.println("<P>[<A HREF=/"../index.jsp/">Restart</A>]");         out.println("<h2> Session Destroyed Successfully</h2>");         out.println("Look at the OC4J Console to see whether the                      HttpSessionEvent was invoked");         out.close();   }}
原创粉丝点击