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.
Servletrequestlistener interface for monitoring the creation and destruction of ServletRequest objects
When the request object is created, the requestinitialized (Servletrequestevent sre) method is called
When the request object is destroyed, the requestdestroyed (Servletrequestevent sre) method is called
1. Write the source code to monitor the creation and destruction of ServletRequest domain objects
Implement Servletrequestlistener interface, monitor the creation and destruction of ServletRequest objects
PackageCom.servlet.listener;ImportJavax.servlet.ServletRequestEvent;ImportJavax.servlet.ServletRequestListener;/** * Simple implementation of the Servletrequestlistener interface, can be ServletRequest object creation and destruction of these two actions to listen. * @author Fan Fangming * * Public class Easyservletrequestlistenerimplements Servletrequestlistener { @Override Public void requestinitialized(Servletrequestevent SRE) {System.out.println ("-----------"+ sre.getservletrequest () +", ServletRequest create"); }@Override Public void requestdestroyed(Servletrequestevent SRE) {System.out.println ("-----------"+ sre.getservletrequest () +", ServletRequest destroyed"); }}
2. Modify Web. xml
<listener> <description>ServletRequestListener监听器</description> <!--实现了ServletRequestListener接口的监听器类 --> <listener-class>com.servlet.listener.EasyServletRequestListener</listener-class> </listener>
3. index.jsp for testing
<%@ page language="java" import="java.util.*" pageencoding= "UTF-8"%><! DOCTYPE html><html> <head> <title>My JSP ' index.jsp ' starting page</title> </head> <body>This is my JSP page.<br>To access the JSP page, the HttpSession is created with the following ID: ${pagecontext.session.id}</body></html>
4. Operation result
Start Web middleware, access from URL:
http://127.0.0.1:8080/webStudy/index.jsp
Console input Results:
——— –[email protected],servletrequest Create
--[email Protected],httpsession Object creation
——— –[email Protected],servletrequest destroyed
A good memory is better than a bad pen. 41-javaweb application in ServletRequest domain monitoring (5)