要实现监听request内置对象,必须实现一个接口javax.servlet.ServletRequsetListener.
代码如下:
package cn.wangkai.listener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class RequestListener implements ServletRequestListener {//实现ServletRequestListener,然后复写下面两个方法
@Override
public void requestDestroyed(ServletRequestEvent event) {
System.out.println("销毁request时候触发"+event.getServletContext());
}
@Override
public void requestInitialized(ServletRequestEvent event) {
System.out.println("产生request时候触发"+event.getServletContext());
}
}
这样做还不够,必须修改web.xml配置如下
......
<listener>
<listener-class>cn.wangkai.listener.RequestListener</listener-class>
</listener>
......
它不需要像servlet样配置映射路径 起名字,只需要把文件路径 cn.wangkai.listener.RequestListener 加进去即可
随便运行个客户端请求 得到结果如下
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
四月 24, 2019 1:56:22 下午 org.apache.catalina.core.StandardContext reload
信息: Reloading Context with name [/mvcpro1] is completed
产生request时候触发org.apache.catalina.core.ApplicationContextFacade@1a8d3a67
销毁request时候触发org.apache.catalina.core.ApplicationContextFacade@1a8d3a67
监听成功