Servlet listener details

Keywords: Session Java Attribute xml

The Servlet API provides a basic application event listener interface. By implementing these Servlets 2.4, programmers can provide event monitoring for the following objects:

  • ServletContext: It can let the program know how the whole application is loaded and unloaded.
  • HttpSession: Web programs can understand and respond to the status of applications during sessions;
  • WebServletRequest enables Web programs to control the lifecycle of Web requests.

The Java Servet API official documentation describes each event listener interface.

Listener Interface Description

ServletContextListener

The package: javax.servlet
Interface declaration: public interface ServletContextListener extends
java.util.EventListener
Method:
1. Void context Destroyed (ServletContextEvent sce); when the application is uninstalled, it triggers the execution of the code in this method.
2. Void context Initialized (ServletContextEvent sce); triggers the execution of code in this method when the application is initialized.

Here we need to explain to ServletContentEvent that it is an event of a ServletContext object whose class is declared as follows:

public class ServletContentEvent extends java.util.EventObject

Including method:

ServletContext getServletContext(), returns the Servlet above the event, the current application that generated the event.

ServletContextAttributeListener

The package: javax.servlet
Interface declaration: public interface ServletContextAttributeListener
extends java.util.EventListener
Method:
1. void attributeAdded(ServletContextAttributeEvent scab); when a new attribute is added to the context of the Servlet, the code in the method is triggered.
2. Void attributeRemove (ServletContextAttributeEvent scab); when an attribute is removed from the context of the servlet, the code in the method is triggered.
3. void attributeReplaced(ServletContextAttributeEvent scab); the code in this method is triggered when the value of an attribute in the servlet context is replaced.

ServletContextAttributeEvent is an event of attributes in the servlet context, and its class declaration is as follows:

public class ServletContextAttributeEvent
extends ServletContextEvent

Including method:

  • String GetName(); returns the name of the attribute that generated the event;
  • Object GetValue(); Returns the value of the attribute that generated the event.

HttpSessionListener

The package: javax.servlet
Interface declaration: public interface HttpSessionListener
extends java.util.EventListener
Method:
1. Void session Created (HttpSession Event); when a session is created, the code in this method is triggered to execute.
2. Void session Destroyed (HttpSession Event se); when a session is released, the code in this method is triggered to execute.

HttpSessionEvent is a session event class, which is declared as follows:

public class HttpSessionEvent
extends java.util.EventObject

Containing method: HttpSession getSession(), returns the session object that generated the event.

HttpSessionActivationListener

The package: javax.servlet
Interface declaration: public interface HttpSession Activation Listener
extends java.util.EventListener
Method:
1. void SessionDidActivate(HttpSessionEvent se)
2. void SessionWillPassivate(HttpSessionEvent se)

Activate and Passivate are actions used to replace objects. When session objects have to be temporarily stored on hard disk or other storage devices (through object serialization) for resource utilization or load balancing reasons, the actions they do are called Passivate, and the actions they take when session objects on hard disk or storage reload JVM are called Activate.

HttpSessionAttributeListener

The package: javax.servlet
Interface declaration: public interface HttpSession AttributeListener
extends java.util.EventListener
Method:
1. void attributeAdded(HttpSessionBindingEvent se)
2. void attributeReplaced(HttpSessionBindingEvent se)
3. void attributeRemoved(HttpSessionBindingEvent se)

The above three methods trigger execution when session attributes are added, session attribute values are modified, and session attributes are removed.

HttpSessionBindingEvent is a session event object class, which is declared as follows:

public interface HttpSessionBindingListener
extends java.util.EventListener

Including method:

  • String getName(), which returns the property name of the session that generated the current event.
  • Object getValue(), which returns the attribute value of the session that generated the current event.
  • HttpSession getSession(), which returns the session object that generated the current event.

HttpSessionBindingListener

The package: javax.servlet
Interface declaration: public interface HttpSession BindingListener
extends java.util.EventListener
Method:

  1. Void value bound (HttpSession Binding Event event); when an object that implements the HttpSession Binding Listener interface is bound to Session Attribute
    This method of the object is executed.

  2. Void value Unbound (HttpSession Binding Event event); when an object implementing the HttpSession Binding Listener interface is unbound from Session Attribute, this method of the object is executed.

Note the difference between HttpSession Attribute Listener and HttpSession Binding Listener:

  1. The former needs to be described in web.xml, while the latter does not.
  2. The former triggers the execution of the code in its method when the genital change of any session occurs, while the latter triggers the execution of the valueBound and valueUnbound methods of that object only when the object that implements it is bound to the session property or unbounded from the session genital. For example, two objects A and B implement the HttpSession BindingListener interface. When A is bound to session properties, only the valueBound() method of A is triggered to execute.

ServletRequestListener

The package: javax.servlet
Interface declaration: public interface ServletRequestListener
extends java.util.EventListener
Method:

  1. void RequestDestroyed(ServletRequestEvent evt)
  2. void RequestInitialized(ServletRequestEvent evt)

The above two methods trigger execution when the ServetRequest object is initialized and cleaned up, respectively. ServletRequestEvent represents the ServletReuest event class, which is declared as follows:

public class ServletRequestEvent
extends java.util.EventObject

Including method:

  • ServletContext getServletContext(), which obtains the context object of the current Web application.
  • ServletRequest getServletRequest(), which obtains the main ServletRequest object of the current event.

ServletRequestAttributeListener

The package: javax.servlet
Interface declaration: public interface ServletRequestAttributeListener
extends java.util.EventListener
Method:

  1. Void attributeAdded (ServletRequestAttributeEvent); this method is triggered when an attribute is added to the ServlvetRequest object attribute.

  2. Void attributeRemove (ServletRequestAttributeEvent); this method is triggered when the attribute is removed from the ServlvetRequest object attribute.

  3. Void attributeReplaced (ServletRequestAttributeEvent); this method is triggered when the generic birth value of the ServlvetRequest object attribute is modified.

ServletRequestAttributeEvent is a ServletRequest attribute event class, which is declared as follows:

public class ServletRequestAttributeEvent
extends ServletRequestEvent

Including method:

  • String getName(), gets the name of the attribute that triggered the event.
  • Object getValue(), which obtains the generic value of the trigger event.

Monitor registration

The following explains how to deploy event listeners in web.xml to handle events in the following format:

<listener>
    <listener-class>
        fey.servlet.listener.CustomServletContextListener
    </listener-class >
</listener>

Among them, fey.servlet.listener.CustomServletContextListener is the class name that implements the aforementioned event listener interfaces. Of course, you need to put these classes in the Web application classes or lib directory of the Web container so that the Web container can be found.

In addition, a class can have one or more listener interfaces.

The listener case

Statistics and display online users

Simple Example 1: Monitor users'online and exit, and display online users

Login.jsp

<%@page pageEncoding="gb2312" contentType="text/html;charset=gb2312" %>
<%
    session=request.getSession(false);
    if(session!=null)session.invalidate();
%>
<html>
    <head><title></title></head>
    <body>
        <form action="isOnline.jsp" method="post">
            //User name: <input type="text" name="uName"/>
            <input type="submit" value=" Go online">
        </form>
    </body>
</html>

2. Control pages (just to illustrate the listener problem, so it's a little simpler...) isOnline.jsp

<%@page pageEncoding="gb2312" contentType="text/html;
charset=gb2312" %>
<html>
    <head><title></title></head>
    <body>
        <%
        session=request.getSession();
        session.setAttribute("userName",
                request.getParameter("uName"));
        response.sendRedirect("showOnline.jsp");
        %>
    </body>
</html>

3. showOnline.jsp Display Page

<%@page pageEncoding="gb2312" contentType="text/html; charset=gb2312"
import="java.util.ArrayList" %>
<html>
<head><title></title></head>
    <body>
        <%
            ArrayList
            showList=
                (ArrayList(getServletContext().
                    getAttribute("list"));
            out.print(" Online number "+showList.size()+"<br>");
            for(int i=0;i<showList.size();i++){
                out.print(showList.get(i)+" On-line"+"<br>");
            }
        %>
        <br>
        <a href="Login.jsp"> Sign out</a>
    </body>
</html>

Configuration page web.xml

<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <listener>
        <listener-class>
            org.xiosu.listener.onlineListener
        </listener-class>
    </listener>
</web-app>

5. listener onlineListener.java

package org.xiosu.listener;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class onlineListener implements HttpSessionListener,
HttpSessionAttributeListener {
    // parameter
    ServletContext sc;
    ArrayList list = new ArrayList();

    // Trigger this action when you create a new session
    public void sessionCreated(HttpSessionEvent se) {
        sc=se.getSession().getServletContext();
        System.out.println(" Build a new one. session");
    }

    // Trigger this action when a session is destroyed
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println(" Destroy one session");
        if (!list.isEmpty()) {
            list.remove((String) se.getSession()
                .getAttribute("userName"));
            sc.setAttribute("list", list);
        }
    }

    // This action is triggered when an object is added to the session, and an object is added to the list
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        list.add((String) sbe.getValue());
        sc.setAttribute("list", list);
    }

    // Trigger this action when you modify or delete an object added to a session
    public void attributeRemoved(HttpSessionBindingEvent arg0) {
    }

    public void attributeReplaced(HttpSessionBindingEvent arg0) {
    }
}

For the application of listeners in Web development, first of all, declarations should be made in the web.xml configuration file: declarations in the web.xml file are as follows: (declaration fragments) after the filter filter filter declaration and filter-mapping declaration.

<listener>
    <listener-class>
        markchen.web.listener.MySessionListener
    </listener-class>
</listener>
<listener>
    <listener-class>
        markchen.web.listener.MyServletContextListener
    </listener-class>
</listener>
// The content of both java classes is simple, just for demonstration purposes.
//The contents of MySessionListener.java file are as follows
//Implementation of Session Lifecycle Listener in Web Applications
package markchen.web.listener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
// This method is called when the session is created, where you can write program code that you need to do special processing.
    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        String sessionId=session.getId();
        System.out.println("Session::::::"+
            sessionId+"******Created******");
    }
    // This method is called when the session is about to be destroyed, where you can write your own program code that needs special processing.
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        String sessionId=session.getId();
        System.out.println("Session::::::"+
            sessionId+"******Destroyed******");
    }
}

Note: The session.invalidate() method must not be called again in the session Destroyed () method, because every call to the session.invalidate() method triggers a call to the session Destroyed () method, which then forms a dead loop and eventually causes the unexpected termination of the Web application.

//MyServletContextListener.java
//Implementation of life cycle listeners for Web applications
package markchen.web.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener
{
    // This method is called after the Web application is initialized
    public void contextInitialized(ServletContextEvent event) {
        System.out.println("******Application
        started******");
    }
    // This method is called when a Web application is destroyed
    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("******Application
        ended******");
    }
}

Posted by four4swords on Sat, 20 Apr 2019 15:57:34 -0700