Servlet Custom Session Binding Listener : HttpSessionBindingListener « Servlet « Java Tutorial






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

public class MyServlet extends HttpServlet {
   
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    // Add a CustomBindingListener
    session.setAttribute("bindings.listener",
                         new CustomBindingListener(getServletContext()));

    out.println("This page intentionally left blank");
  }
}

class CustomBindingListener implements HttpSessionBindingListener {

  // Save a ServletContext to be used for its log() method
  ServletContext context;

  public CustomBindingListener(ServletContext context) {
    this.context = context;
  }

  public void valueBound(HttpSessionBindingEvent event) {
    context.log("[" + new Date() + "] BOUND as " + event.getName() +
                " to " + event.getSession().getId());
  }

  public void valueUnbound(HttpSessionBindingEvent event) {
    context.log("[" + new Date() + "] UNBOUND as " + event.getName() +
                " from " + event.getSession().getId());
  }
}
<?xml version="1.0" encoding="ISO-8859-1"?>

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

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>

             
    </servlet>
    
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
  Download:  ServletCustomSessionBindingListener.zip( 89 k)








25.7.HttpSessionBindingListener
25.7.1.Servlet Custom Session Binding Listener