A listener is an object that listens to and handles events or state changes that occur on other objects and takes action immediately when the object being monitored occurs.
The listener in Javaweb is a special class defined in the servlet specification that listens to the creation and destruction events of ServletContext, HttpSession, and ServletRequest domain objects in a Web application. and listening for events in which the properties in these domain objects have been modified.
1, the servlet Listener classification
Several types of listeners are defined in the servlet specification, which are used to listen for three domain objects of the event source Servletcontext,httpsession and ServletRequest;
For operations on these three domain objects, the listener is divided into three types:
1. Listen for event listeners that are created and destroyed by the domain object itself.
2. Listen for added and deleted event listeners for the properties in the domain object.
3. Listen for event listeners that are bound to the state of an object in the HttpSession domain.
2. Monitoring the creation and destruction of ServletContext domain objects
The Servletcontextlistener interface is used to listen for ServletContext object creation and destruction events. Classes that implement the Servletcontextlistener interface can listen to the creation and destruction of ServletContext objects.
The contextinitialized (Servletcontextevent SCE) method is called when the ServletContext object is created.
The contextdestroyed (Servletcontextevent SCE) method is called when the ServletContext object is destroyed.
3. Write the source code to monitor the creation and destruction of ServletContext domain objects
Implement Servletcontextlistener interface, monitor the creation and destruction of ServletContext objects
PackageCom.servlet.listener;ImportJavax.servlet.ServletContextEvent;ImportJavax.servlet.ServletContextListener;/** * Simple implementation of the Servletcontextlistener interface, can be ServletContext object creation and destruction of these two actions to listen. * @author Fan Fangming * * Public class Easyservletcontextlistenerimplements Servletcontextlistener { @Override Public void contextinitialized(Servletcontextevent SCE) {System.out.println ("-----------ServletContext object Creation"); }@Override Public void contextdestroyed(Servletcontextevent SCE) {System.out.println ("-----------ServletContext object Destruction"); }}
4. Modify Web. xml
<listener>
<description>ServletContextListener监听器</description>
<!--实现了ServletContextListener接口的监听器类 -->
<listener-class>com.servlet.listener.EasyServletContextListener</listener-class>
</listener>
5. Operation Result
Start the Web middleware and see the console output:
——— –servletcontext Object creation
A good memory is better than a bad writer. Listeners in 39-javaweb applications (1)