I. BACKGROUND
Each time Tomcat is started, the console console outputs a variety of information, which is seen in both messages
[XXX 2018-06-04 15:52:13,772] (DEBUG)-Xxx.xxx.basic.listener.StartUpListener-(startuplistener.java:53) xxx start initialization started
[XXX 2018-06-04 15:52:13,783] (DEBUG)-Xxx.xxx.basic.listener.StartUpListener-(startuplistener.java:57) xxx start initialization end
Why do you print two messages each time you start Tomcat, and in order to find out, we get into this class?
@WebListener ("Startuplistener") public class Startuplistener implements Servletcontextlistener {/* * log4j logging */protected final Logger log = Logger.getlogger (This.getclass ());/** * * Monitoring project started, Initialize * * @param SCE * Servletcontextevent Object */@Overridepublic void contextinitialized (Servletcontextevent SCE) {//TODO auto-generated method stublog.debug ("XXX start initialization start"); Const.context = Webapplicationcontextutils.getwebapplicationcontext (Sce.getservletcontext ()); Const.project_path = Sce.getservletcontext (). Getrealpath (Const.separator); Const.base = Sce.getservletcontext (). Getcontextpath (); Log.debug ("XXX Start initialization End");} /** * Monitoring item terminated, destroyed * * @param SCE * Servletcontextevent Object */@Overridepublic void contextdestroyed (Servletcontex Tevent SCE) {//TODO auto-generated Method stub}}
in this class, you see the following words, " listen to project start, initialize " and "Listen for project termination, destroy", and find the previous log information in the Contextinitialized method. Seeing this class inherit the Servletcontextlistener, it is not difficult to conclude that the function of this method is to monitor the startup process of the project when Tomcat starts. So why does this approach enable monitoring?
Ii. introduction of Listener
Listener is the listener, which is the listener for the servlet. Launched with the launch of the Web app, initialized only once, and destroyed with the Web app's stop (implemented through the observer design pattern). The main role is to do some initialization of the content to add work, set some basic content, such as some parameters or some fixed object, through the listener, you can automatically fire some actions. For example: Listen to the number of online users and so on.
There is a Servletcontextlistener interface in the Servlet API that listens to the life cycle of a ServletContext object, and in effect listens to the life cycle of a WEB application. The Servletcontextevent event is triggered when the servlet container starts or terminates the Web app, and the event is handled by Servletcontextlistener. The two methods for handling Servletcontextevent events are defined in the Servletcontextlistener interface:
Public interface Servletcontextlistener extends EventListener { //the method is called when the servlet container launches the Web App. After the method is called, the container initializes the filter and initializes the servlet that needs to be initialized when the Web app starts. Public void contextinitialized (Servletcontextevent sce); This method is called when the servlet container terminates the Web App. Before calling this method, the container destroys all servlets and filter filters first. Public void contextdestroyed (Servletcontextevent sce);
Third, case analysis
Back to the beginning of the question, the Startuplistener class implements the Servletcontextlistener interface, by configuring the @weblistener ("Startuplistener") to listen for annotations, when the project starts, Call the Contextinitialized method to print the log of the project startup and initialize some parameters. In addition, if you do not use annotations to implement monitoring, you can also configure the Listener class in Web. xml
<!--Spring Monitoring project startup process, initializing parameters--><listener> <listener-class> Xxx.xxx.basic.listener.StartUpListener </listener-class> </listener>
Iv.Servlet Listener Interface and event objects
By listener: There are three types of events defined by the servlet2.4 specification:
1. Event listeners for listening to application environment objects (ServletContext)
2. Event listeners for listening to user session objects (HttpSession)
3. Event listener for listening on request message object (ServletRequest)
The Servlet API provides the following listener interfaces: Javax.servlet.AsyncListener-If an asynchronous operation started on a servletrequest that has been added to the listener has completed, timed out, or caused an error, the listener will be notified. Javax.servlet.ServletContextListener-an interface for receiving notification events about ServletContext life cycle changes. Javax.servlet.ServletContextAttributeListener-an interface that receives notification events about the ServletContext property change. Javax.servlet.ServletRequestListener-an interface for receiving notification events about entering and exceeding a Web application-wide request. Javax.servlet.ServletRequestAttributeListener-an interface that receives notification events about the ServletRequest property change. Javax.servlet.http.HttpSessionListener-Interface to receive notification events about httpsession life cycle changes. Javax.servlet.http.HttpSessionBindingListener-Causes the object to be notified from the session to the binding or from the time it is bound. Javax.servlet.http.HttpSessionAttributeListener-an interface for receiving notification events about the HttpSession property change. Javax.servlet.http.HttpSessionActivationListener-Objects bound to sessions may listen for container events, notifying them that the session will be passivated and the session will be activated. A container for migrating sessions between VMS or persistent sessions is required to notify all properties that are bound to the session that implements Httpsessionactivationlistener.
By listening for event class items
1. Event listeners for monitoring the creation and destruction of domain objects themselves
2. Event listeners to listen for additions and deletions of properties in domain objects
3. Event listener for listening to the state of an object bound to an HttpSession domain
The Servlet API provides the following event object: Javax.servlet.AsyncEvent-in ServletRequest (by calling Servletrequest#startasync or servletrequest# Startasync (Servletrequest,servletresponse)) initiates an asynchronous operation that has completed, timed out, or caused an error when an event is triggered. Javax.servlet.http.HttpSessionBindingEvent-sends this type of event to an object that implements Httpsessionbindinglistener, when the object is bound or unbound from the session, or send to the Httpsessionattributelistener configured in Web. XML, unbind or replace in the session when any property is bound. The session binds the object through a call to Httpsession.setattribute and unbind the object by calling Httpsession.removeattribute. When an object is removed from the session, we can use this event for cleanup activities. Javax.servlet.http.HttpSessionEvent-This is the class that represents the event notification for a session change in the Web application. Javax.servlet.ServletContextAttributeEvent-event class for notification of changes to the ServletContext properties of the Web application. Javax.servlet.ServletContextEvent-This is the event class for notifications of servlet context changes for Web applications. Javax.servlet.ServletRequestEvent-Such events represent ServletRequest lifecycle events. The source code of the event is the ServletContext of this Web application. Javax.servlet.ServletRequestAttributeEvent-This is the event class that is used to notify the changes to the properties of the servlet request in the application.
During the entire run of a Web application, the Web container creates and destroys three important objects, servletcontext,httpsession,servletrequest.
V. Simple examples
Custom session Scanner
Package Com.github.listener;import Java.util.collections;import Java.util.linkedlist;import java.util.List;import Java.util.timer;import Javax.servlet.servletcontextevent;import Javax.servlet.http.httpsession;import Javax.servlet.http.httpsessionevent;import javax.servlet.http.httpsessionlistener;/** * Listener: When the website user volume increases, Session occupies more and more memory, then the session management, will be a very large system overhead, in order to effectively manage the session, * we can write a listener, regularly clean out the expired session * * @author Raosiwen * @date June 4, 2018 PM 5:20:31 */public class Sessionscanerlistener implements Httpsessionlistener {//Create a thread-safe collection, Used to store sessionlist
Package Com.github.listener;import Java.util.list;import Java.util.listiterator;import java.util.TimerTask;import javax.servlet.http.httpsession;/** * Timer, define the specific contents of the timed task * * @author Raosiwen * @date June 4, 2018 PM 5:52:24 */public class M Ytask extends TimerTask {private list
To add a context configuration in Web. xml
<!--the configuration of the spring listener for monitoring session memory--><listener><listener-class> Com.github.listener.sessionscanerlistener</listener-class></listener>
Vi. Summary
At this point, through the listener case analysis of the servlet and the simple sample, we can know that listener and servlet, filter has a common point, all are dispatched by the container. We just need to write our own listener to implement the listener interfaces we care about and register, and the rest of the work is to write business logic in our own listener.
Reference: Https://www.cnblogs.com/EasonJim/p/7100750.html and 52891311
Java listener--Monitor each action of the servlet