JavaWeb Speed Listener

Table of contents

1. Quick Start with Listener

        1.Listener introduction:  

        2.Java event processing mechanism: 

二、ServletContextListener

        1. Function: 

        2. Related methods: 

        3. Application examples: 

三、ServletContextAttributeListener

        1. Function: 

        2. Related methods: 

        3. Application examples: 

4. HttpSessionListener

        1. Function: 

        2. Related methods: 

        3. Application examples: 

5. Other monitors

        1.HttpSessionAttributeListener : 

            1.1 Function 

            1.2 Related methods

        2.ServletRequestListener : 

            2.1 Function

            2.2 Related methods

        3.ServletRequestAttributeListener : 

            3.1 Function

            3.2 Related methods


1. Quick Start with Listener

       1.Listener introduction:  

        (1) Listener is one of the three major components of JavaWeb . The three major components of JavaWeb are: Servlet program , Listener , and Filter .
        (2) Listener is a JavaEE specification, which is an interface.
        (3) The function of  the listener is to monitor certain changes ( usually the creation/destruction of objects, changes in attributes ), and trigger the corresponding method to complete the corresponding task.
        (4) There are 8 listeners in  JavaWeb , the most commonly used of which is ServletContextListener.

       2.Java event processing mechanism: 

        Java's event processing adopts the " delegated event model ". That is, when an event occurs, the object of the event is generated and the relevant information is passed to the "event listener" for processing .
        Among them -
        ①The event source refers to the user's operation, which can be a button or a window, that is, the object that generates the event object;

        ②Events are event objects that carry information generated when the event source state changes, such as keyboard events, window events, mouse events, etc. This object stores a lot of information about the current event, such as the KeyEvent object containing the Code of the currently pressed key. value. Various event types are defined under the java.awt.event package and javax.swing.event package.


二、ServletContextListener

        1. Function: 

        Monitor the creation or destruction of ServletContext (  the ServletContext object is created when the web application starts ), that is, life cycle monitoring.
        Application scenarios——
        (1) Load the initialization configuration file; eg: Spring configuration file
        (2) Task scheduling (cooperating with timer Timer/TimerTask)

        2. Related methods: 

        (1) void contextInitialized(ServletContextEvent sce) is triggered when creating a ServletContext object
        (2) void contextDestroyed(ServletContextEvent sce) is triggered when the ServletContext object is destroyed

        3. Application examples: 

                The web.xml configuration file is as follows: 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <listener>
        <listener-class>listener.IntroListener</listener-class>
    </listener>
</web-app>

               The IntroListener class code is as follows: 

package listener;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;

/** Δ注意事项 : 
    (1) 当一个类实现了ServletContextListener接口,该类就是一个监听器。
    (2) 该类可以监听的事件,由该类实现的监听接口决定,
        eg: 实现了ServletContextListener接口,就可以监听ServletContextListener对象
            的创建和销毁,以此类推。
    (3) 当Web应用启动时,会产生ServletContextEvent事件对象,会调用对应的监听器的事件
        处理方法,此处为contextInitialized(...)方法,同时会传递事件对象。
    (4) 程序员可以通过ServletContextEvent事件对象,来获取需要的信息,然后再进行相应的业务处理。
    (5) Tomcat有维护一个容器来管理Listener.
 */
public class IntroListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        System.out.println("获取到的ServletContext对象 = " + servletContext);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        System.out.println(servletContext + "————ServletContext对象被销毁~");
    }
}

                operation result: 


三、ServletContextAttributeListener

        1. Function: 

        Monitor ServletContext property changes

        2. Related methods: 

        (1) void attributeAdded(ServletContextAttributeEvent event) is called when adding an attribute
        (2) void attributeReplaced(ServletContextAttributeEvent event) is called when replacing an attribute
        (3) void attributeRemoved(ServletContextAttributeEvent event) is called when removing an attribute

        3. Application examples: 

               The web.xml configuration file is as follows: 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <listener>
        <listener-class>listener.IntroListener</listener-class>
    </listener>
    <listener>
        <listener-class>listener.ServletContextAttribute</listener-class>
    </listener>
</web-app>

                The ServletContextAttribute class code is as follows: 

package listener;

import jakarta.servlet.ServletContextAttributeEvent;
import jakarta.servlet.ServletContextAttributeListener;

/**
 * @author : Cyan_RA9
 * @version : 21.0
 */
public class ServletContextAttribute implements ServletContextAttributeListener {
    @Override
    public void attributeAdded(ServletContextAttributeEvent scae) {
        String name = scae.getName();
        Object value = scae.getValue();
        System.out.println("监听到\"" + name + " = " + value + "\"属性被添加");
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent scae) {
        //Δ该方法取得的属性为旧值。

        String name = scae.getName();
        Object value = scae.getValue();
        System.out.println("监听到\"" + name + " = " + value + "\"属性被修改");
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent scae) {
        String name = scae.getName();
        Object value = scae.getValue();
        System.out.println("监听到\"" + name + " = " + value + "\"属性被删除");
    }
}

                The TestServlet class code is as follows: 

package listener;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(urlPatterns={"/test"})
public class TestServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = getServletContext();

        servletContext.setAttribute("color", "cyan");
        servletContext.setAttribute("color", "pink");

        servletContext.removeAttribute("color");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

                Running results: (GIF)


4. HttpSessionListener

        1. Function: 

        Monitor the creation or destruction of Session objects, that is, Session life cycle monitoring.

        2. Related methods: 

        (1) void sessionCreated(HttpSessionEvent se) is called when creating the Session object         (2) void sessionDestroyed(HttpSessionEvent se) is called when the Session object is destroyed

        3. Application examples: 

                The HttpSessionListener_Demo class code is as follows: 

package listener;

import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;

public class HttpSessionListener_Demo implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        String sessionId = session.getId();
        System.out.println("Session" + sessionId + "被创建.");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        String sessionId = session.getId();
        System.out.println("Session" + sessionId + "被销毁.");
    }
}

                Configure the Listener in the web.xml configuration file, as shown in the following figure: 

                The TestServlet2 class code is as follows: 

package listener;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet(urlPatterns = {"/test2"})
public class TestServlet2 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        System.out.println("session = " + session);

        String threadName = Thread.currentThread().getName();
        System.out.println("令" + threadName + "线程休眠10秒钟~");
        try {
            Thread.sleep(1000 * 10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        session.invalidate();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

                Running results: (GIF below)


5. Other monitors

        1.HttpSessionAttributeListener : 

            1.1 Function 

        Monitor changes in Session properties

            1.2 Related methods

        (1) void attributeAdded(ServletRequestAttributeEvent srae) when adding attributes to the Session object
        (2) void attributeReplaced(ServletRequestAttributeEvent srae) when replacing attributes in the Session object
        (3) void attributeRemoved(ServletRequestAttributeEvent srae) when removing attributes in the Session object

        2.ServletRequestListener : 

            2.1 Function

        Monitor the creation or destruction of Req objects , that is, Request object life cycle monitoring.

            2.2 Related methods

        (1) void requestInitialized(ServletRequestEvent sre) is called when creating a request object ; the ServletRequest object can be obtained through the ServletRequestEvent object, and then through polymorphic downward transformation, the implementation class object of the HttpServletRequest interface can be obtained .
        (2) void requestDestroyed(ServletRequestEvent sre) is called when destroying the request object .

        3.ServletRequestAttributeListener : 

            3.1 Function

        Monitor the property changes of Req . ( First called ; combined with Tomcat's underlying mechanism, Tomcat will process HTTP requests through the HttpServletRequest object )

            3.2 Related methods

        (1) void attributeAdded(ServletRequestAttributeEvent srae) when adding attributes
        (2) void attributeReplaced(ServletRequestAttributeEvent srae) when replacing attributes
        (3)  void attributeRemoved(ServletRequestAttributeEvent srae) when removing attributes  

        System.out.println("END----------------------------------------------------------------------------------------------------------------------------------");

Guess you like

Origin blog.csdn.net/TYRA9/article/details/132348975