[Spring Boot Series] - Spring Boot Listener Listener

[Spring Boot Series] - Spring Boot Listener Listener


Insert image description here

I. Overview

What is a web listener? Web listeners are special classes in Servlets . They can help developers monitor specific events in the web, such as the creation and destruction of ServletContext, HttpSession, and ServletRequest; the creation, destruction, and modification of variables, etc. You can add processing before and after certain actions to implement monitoring and so on. There are many usage scenarios for web listeners; Spring's listener is an observer pattern, which can directly decouple events from event listeners;

2. Listener classification

2.1 Listening to the event listener of ServletContext

They are: ServletContextListener, ServletContextAttributeListener. At the Application level, there is only one for the entire application and can be configured globally.

2.2 Listening to the event listener of HttpSeesion

They are: HttpSessionListener, HttpSessionAttributeListener. Session level, for each object, such as counting the total number of sessions.

2.3 Event listener for listening to ServletRequest

They are: ServletRequestListener, ServletRequestAttributeListener. Request level, for each customer request.

3. Listeners in SpringMVC

3.1 ContextLoaderListener

When starting the web container, the configuration information of Spring applicationContext.xml is automatically assembled. Because it implements the ServletContextListener interface, configure this listener in web.xml, and when the container is started, the method it implements will be executed by default. The ContextLoader class is associated with the ContextLoaderListener, so the entire loading and configuration process is completed by the ContextLoader.

The following is the configuration of ContextLoaderListener and context in web.xml

<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

context-param

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

ServletContextListener is the listener of ServletContext. If the ServletContext changes, for example, the ServletContext is created when the server starts, and the ServletContext will be destroyed when the server shuts down.

3.2 RequestContextListen

Bind the HTTP request object to the thread that services the request based on LocalThread. This allows beans with request and session scope to be accessed later in the call chain.

  • Request scope
<bean id="loginAction" class="com.goyeer.LoginAction" scope="request"/>  

For each HTTP request, the Spring container will create a new LoginAction bean instance based on the loginAction bean definition, and the loginAction bean instance is only valid within the current HTTP request, so you can safely change the internal state of the created instance as needed, while other Instances created from the loginAction bean definition in a request will not see these request-specific state changes. When processing the request ends, the bean instance in the request scope will be destroyed.

  • Session scope
<bean id="user" class="com.goyeer.User" scope="session"/>

For a certain HTTP Session, the Spring container will create a new userPreferences bean instance based on the userPreferences bean definition, and the userPreferences bean is only valid within the current HTTP Session. Like the request scope, you can safely change the internal state of the created instance as needed, while instances created based on userPreferences in other HTTP Sessions will not see these state changes specific to a certain HTTP Session. When the HTTP Session is eventually discarded, the beans within the scope of the HTTP Session will also be discarded.

  • global session scope
<bean id="userPrefere" class="com.goyeer.userPrefere" scope="globalSession"/> 

The global session scope is similar to the standard HTTP Session scope, but it only makes sense in portlet-based web applications. The Portlet specification defines the concept of a global Session, which is shared by all the different portlets that make up a portlet web application. Beans defined in the global session scope are limited to the life cycle scope of the global portlet Session. Please note that if you are writing a standard Servlet-based web application and define one or more beans with global session scope, the system will use the standard HTTP Session scope and will not cause any errors.

3.3 IntrospectorCleanupListener

  • The role and impact of Introspector

Before analyzing IntrospectorCleanupListener, let’s first understand Introspector. Introspector is a class under the java.beans package in the JDK. It provides a standard method for the target JavaBean to understand the original class methods, properties and events. In layman's terms, you can build a BeanInfo object through Introspector, and this BeanInfo object contains description information of properties, methods and events in the target class, and then you can use this BeanInfo object to perform related operations on the target object.

Introspector indirectly holds a strong reference to BeanInfo. If you use the Introspector to operate many classes, the Introspector will indirectly hold strong references to these BeanInfos. When garbage collection occurs, if it is detected that these BeanInfos have reference chains, these classes and corresponding class loaders will not be recycled by the garbage collector, resulting in memory leaks. Therefore, in order to solve this problem, after the operation using the Introspector is completed, call the flushCaches method of the Introspector class to clear the cache.

  • PlaceIntrospectorCleanupListener

This listener is mainly used to solve the memory leak problem caused by java.beans.Introspector. The purpose of the java.beans.Introspector class in the JDK is to discover whether a Java class conforms to the JavaBean specification. If some framework or program uses the Introspector class, a system-level cache will be enabled, which will store references to some JavaBeans that have been loaded and analyzed. When the Web server is shut down, because these JavaBean references are stored in this cache, the garbage collector cannot recycle the JavaBean objects in the Web container, which eventually causes the memory to become larger. The org.springframework.web.util.IntrospectorCleanupListener is an auxiliary class specially used to deal with Introspector memory leak problems. IntrospectorCleanupListener will clean the Introspector cache when the Web server stops so that those Javabeans can be correctly recycled by the garbage collector. Spring itself does not have this problem, because Spring will refresh immediately after loading and analyzing a class. java.beans.-Introspector cache, which ensures that this memory leak problem will not occur in Spring. However, some programs and frameworks do not clean up after using JavaBeans Introspector (such as Quartz, Struts), which eventually leads to memory leaks.

​ In my previous work experience, I have seen many times that the IntrospectorCleanupListener is configured as a non-first listener in web.xml. The official statement is that this listener must be configured as the first listener in web.xml so that it can play the most effective role at the right time. The reason is actually very simple. Before the Servlet3.0 specification, the call of the listener was random. Starting from Servlet3.0, the order of the call of the listener is based on the order configured in web.xml, and the listener of ServletContextListener is implemented. , the calling order of the contextInitialized method is executed in the positive order according to the order configured in web.xml, while the calling order of the contextDestroyed method is executed in the reverse order according to the order configured in web.xml. Therefore, if the Introspector-CleanupListener is configured as the first listener, then its contextDestroyed method will be executed last and will have the most effective cleaning effect; if not, there may be cache that has not been cleared.

4. Web event listener in Servlet API

4.1 ServletContextListener – monitors the creation and destruction of servletContext objects

  • contextInitialized(ServletContextEvent arg0) – executed when created
  • contextDestroyed(ServletContextEvent arg0) – executed when destroyed

4.2 HttpSessionListener – monitors the creation and destruction of session objects

  • sessionCreated(HttpSessionEvent se) – executed when created
  • sessionDestroyed(HttpSessionEvent se) – executed when destroyed

4.3 ServletRequestListener – monitors the creation and destruction of request objects

  • requestInitialized(ServletRequestEvent sre) – executed when created
  • requestDestroyed(ServletRequestEvent sre) – executed when destroyed

4.4 ServletContextAttributeListener – listens for changes in attributes in the servletContext object

  • attributeAdded(ServletContextAttributeEvent event) – executed when an attribute is added
  • attributeReplaced(ServletContextAttributeEvent event) – executed when an attribute is modified
  • attributeRemoved(ServletContextAttributeEvent event) – executed when an attribute is removed

4.5 HttpSessionAttributeListener - listens for changes in attributes in the session object

  • attributeAdded(HttpSessionBindingEvent event) – executed when adding an attribute
  • attributeReplaced(HttpSessionBindingEvent event) – executed when an attribute is modified
  • attributeRemoved(HttpSessionBindingEvent event) – executed when an attribute is removed

4.6 ServletRequestAttributeListener - listens for changes in attributes in the request object

  • attributeAdded(ServletRequestAttributeEvent srae) – executed when an attribute is added
  • attributeReplaced(ServletRequestAttributeEvent srae) – executed when an attribute is modified
  • attributeRemoved(ServletRequestAttributeEvent srae) – executed when an attribute is removed

Guess you like

Origin blog.csdn.net/songjianlong/article/details/132844675