Listener 监听对象的创建和销毁
HttpSessionListener、ServletContextListener、ServletRequestListener分别用于控制Session、context、request的创建和销毁。触发时机分别为:
- HttpSessionListener:监听Session的创建和销毁。创建session时执行sessionCreated(HttpSessionEvent se)方法。超时或者执行session.invalidate()时执行sessionDestroyed(HttpSessionEvent se)方法。该Listener用于收集在线者信息。
- ServletContextListener:监听context的创建和销毁。context代表当前的web应用程序。服务器启动或者热部署war包时执行contextInitialized(ServletContextEvent event)方法。服务器关闭或者只关闭该web时会执行contextDestoryed(ServletContextEvent event)方法。该Listener可用于获取web.xml里配置的初始化参数。
- ServletRequestListener:监听request的创建和销毁。用户每次请求request都会执行requestInitialized(ServletRequestEvent event)方法。request处理完毕自动销毁前执行requestDestoryed(ServletRequestEvent event)方法。如果一个HTML页面内含有多个图片,则请求一次HTML页面可能会出发多次request事件。
package linstener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class LinstenerTest implements HttpSessionListener, ServletContextListener, ServletRequestListener { private Log log =LogFactory.getLog(this.getClass()); @Override public void requestDestroyed(ServletRequestEvent arg0) { //销毁Request时调用 HttpServletRequest request=(HttpServletRequest)arg0.getServletRequest(); long time=System.currentTimeMillis()-(long)request.getAttribute("dateCreated"); log.info(request.getRemoteAddr()+"请求处理结束,用时"+time+"毫秒。"); } @Override public void requestInitialized(ServletRequestEvent arg0) { //创建Request时调用 HttpServletRequest request=(HttpServletRequest) arg0.getServletRequest(); String uri=request.getRequestURI(); uri=request.getQueryString()==null?uri:(uri+"?"+request.getQueryString()); request.setAttribute("dateCreated", System.currentTimeMillis()); log.info("IP:"+request.getRemoteAddr()+" 请求 "+uri); } @Override public void contextDestroyed(ServletContextEvent arg0) { //销毁Servlet上下文时调用 ServletContext servletContext=arg0.getServletContext(); log.info("即将关闭"+servletContext.getContextPath()); } @Override public void contextInitialized(ServletContextEvent arg0) { //加载Servlet上下文时调用 ServletContext servletContext=arg0.getServletContext(); log.info("即将启动"+servletContext.getContextPath()); } @Override public void sessionCreated(HttpSessionEvent arg0) { //创建session时调用 HttpSession session =arg0.getSession(); log.info("新创建一个session,ID为:"+session.getId()); } @Override public void sessionDestroyed(HttpSessionEvent arg0) { //销毁session前调用 HttpSession session =arg0.getSession(); log.info("销毁一个session,ID为:"+session.getId()); } }
Listener类web.xml文件中的配置:
<listener> <listener-class> linstener.LinstenerTest </listener-class> </listener>