ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Servlet App Event Listeners
Pages: 1, 2, 3, 4, 5, 6, 7

Listing 7 is an example of an application event listener that receives all notifications of HttpSession objects; whether the HttpSession object was created or destroyed and if an attribute was added or removed.


Listing 7: An application event listener that handles all notifications of HttpSession objects. (MySessionListener.java)

package com.listeners;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionAttributesListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;



public final class MySessionListener
  implements HttpSessionAttributesListener, HttpSessionListener {


  public void sessionCreated(HttpSessionEvent event) {

    System.out.println("HttpSession object has been created");

  }


  public void sessionDestroyed(HttpSessionEvent event) {

    System.out.println("HttpSession object has been removed");

  }

  public void attributeAdded(HttpSessionBindingEvent event) {

    System.out.println("An attribute has been added " +
      "to an HttpSession object");

  }



  public void attributeRemoved(HttpSessionBindingEvent event) {

    System.out.println("An attribute has been removed " +
      "to an HttpSession object");

  }


  public void attributeReplaced(HttpSessionBindingEvent event) {

    System.out.println("An attribute has been replaced " +
      "to an HttpSession object");

  }
}


It's good to see the code for the application event listener, but let's test it. Listing 8 is the code for a Servlet that maintains a "bank balance" for an individual in an HttpSession object. You can withdraw and deposit money into the account, in increments of $50.


Listing 8: A Servlet that works with an HttpSession object. (BankBalance.java)

package com.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class BankBalance extends HttpServlet
{
  public void service(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException
  {
    response.setContentType("text/html");
    ServletOutputStream out = response.getOutputStream();

    out.print("<?xml version='1.0' encoding='UTF-8'?>");

    out.print("<!DOCTYPE html");
    out.print("PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'");
    out.print("'DTD/xhtml1-strict.dtd'>");

    out.print("<html>");
    out.print("<head>");
    out.print("<title>Maintaining Session State</title>");
    out.print("</head>");
    out.print("<body>");

    out.print("<center>");

    HttpSession session = request.getSession();

    String action = request.getParameter("action");

    Double balance = (Double) session.getAttribute("Balance");
    if (balance == null)
    {
      balance = new Double(500);
      session.setAttribute("Balance", balance);
      out.print(balance.doubleValue());
      out.print("<br />");

    } else {
      double bal = balance.doubleValue();

      if (action.equals("withdraw"))
      {
        bal -= 50;
      } else {
        bal += 50;
      }

      balance = new Double(bal);
      session.setAttribute("Balance", balance);

      out.print("Your new balance is: ");
      out.print(bal);
      out.print("<br />");

    }


    out.print("<a href='./bank?action=deposit'>");
    out.print("Deposit $50");
    out.print("</a>");

    out.print("<br />");

    out.print("<a href='./bank?action=withdraw'>");
    out.print("Withdraw $50");
    out.print("</a>");

    out.print("</center>");

    out.print("</body>");
    out.print("</html>");

  }
}

The web.xml deployment descriptor that defines this Servlet and the application event listener is shown in Listing 9.


Listing 9: The web.xml deployment descriptor showing the BankBalance Servlet definition and the MySessionListener application event listener definition.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

   <!-- Define application events listeners -->
  <listener>
    <listener-class>
      com.listeners.MyContextListener
    </listener-class>
  </listener>

  <listener>
    <listener-class>
      com.listeners.ServletContextAttribListener
    </listener-class>
  </listener>

  <listener>
    <listener-class>
      com.listeners.MySessionListener
    </listener-class>
  </listener>


  <!-- Define servlets that are included in the example application -->
  <servlet>
    <servlet-name>
      simple
    </servlet-name>
    <servlet-class>
      com.servlets.SimpleServlet
    </servlet-class>
  </servlet>

  <servlet>
    <servlet-name>
      bank
    </servlet-name>
    <servlet-class>
      com.servlets.BankBalance
    </servlet-class>
  </servlet>

  <servlet>
    <servlet-name>
      context attribs
    </servlet-name>
    <servlet-class>
      com.servlets.ServletContextAttrib
    </servlet-class>
  </servlet>

  <!-- Define servlet mappings to urls -->
<servlet-mapping>
    <servlet-name>
      simple
    </servlet-name>
    <url-pattern>
      /simple
    </url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>
      bank
    </servlet-name>
    <url-pattern>
      /bank
    </url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>
      context attribs
    </servlet-name>
    <url-pattern>
      /servletcontextattrib
    </url-pattern>
  </servlet-mapping>

</web-app>

Summary

This article shows you how to write application event listeners to handle notifications about changes to the ServletContext object and HttpSession objects. Application event listeners give web application programmers greater control over the ServletContext and HttpSession objects. Although the examples in this article were simplistic, they lay the groundwork for examining these event listeners. Now that you can write listener classes, adding more advanced programming within the notification methods is easy.

Stephanie Fesler is a BEA Systems expert on implementing various Java 2EE API.


Return to ONJava.com.