在部署web应用是产生,即用户第一次访问之前已经产生,在重新部署web应用时,后销毁原监听器,再产生新的监听器
package cn.itcast.web.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; //事件监听器[用于监听ServletContext对象产生和销毁] public class MyServletContextListener implements ServletContextListener{ public MyServletContextListener(){ System.out.println("空参构造"); System.out.println(this.hashCode()); } //产生 public void contextInitialized(ServletContextEvent sce) { System.out.println("ServletContext产生"); System.out.println(this.hashCode()); } //销毁 public void contextDestroyed(ServletContextEvent sce) { System.out.println("ServletContext销毁"); System.out.println(this.hashCode()); } }
package cn.itcast.web.listener; import java.util.Date; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; //监听器[用于监听HttpSesison产生和销毁] public class MyHttpSessionListener implements HttpSessionListener { //产生 public void sessionCreated(HttpSessionEvent se) { HttpSession session = se.getSession(); System.out.println(session.getId()); System.out.println("sessionCreated()" + new Date().toLocaleString()); } //销毁 public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); System.out.println(session.getId()); System.out.println("sessionDestroyed()"); System.out.println("sessionCreated()" + new Date().toLocaleString()); } }
package cn.itcast.web.listener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; //监听器[用于监听ServletRequest对象的产生和销毁] public class MyServletRequestListener implements ServletRequestListener { //产生 public void requestInitialized(ServletRequestEvent sre) { System.out.println("requestInitialized()"); } //销毁 public void requestDestroyed(ServletRequestEvent sre) { System.out.println("requestDestroyed()"); } }