javaWeb:事件监听
事件对象
l ServletContextEvent:ServletContext getServletContext();
l HttpSeessionEvent:HttpSession getSession();
l ServletRequestEvent:
- ServletRequest getServletRequest()
- ServletContext getServletContext()
编写测试例子:
l 编写MyServletContextListener类,实现ServletContextListener接口;
l 在web.xml文件中部署监听器;
l 为了看到session销毁的效果,在web.xml文件中设置session失效时间为1分钟;
/* * ServletContextListener实现类 * contextDestroyed() -- 在ServletContext对象被销毁前调用 * contextInitialized() -- -- 在ServletContext对象被创建后调用 * ServletContextEvent -- 事件类对象 * 该类有getServletContext(),用来获取ServletContext对象,即获取事件源对象 */ public class MyServletContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent evt) { System.out.println("销毁ServletContext对象"); }
public void contextInitialized(ServletContextEvent evt) { System.out.println("创建ServletContext对象"); } } |
/* * HttpSessionListener实现类 * sessionCreated() -- 在HttpSession对象被创建后被调用 * sessionDestroyed() -- -- 在HttpSession对象被销毁前调用 * HttpSessionEvent -- 事件类对象 * 该类有getSession(),用来获取当前HttpSession对象,即获取事件源对象 */ public class MyHttpSessionListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent evt) { System.out.println("创建session对象"); }
public void sessionDestroyed(HttpSessionEvent evt) { System.out.println("销毁session对象"); } }
|
/* * ServletRequestListener实现类 * requestDestroyed() -- 在ServletRequest对象被销毁前调用 * requestInitialized() -- 在ServletRequest对象被创建后调用 * ServletRequestEvent -- 事件类对象 * 该类有getServletContext(),用来获取ServletContext对象 * 该类有getServletRequest(),用来获取当前ServletRequest对象,即事件源对象 */ public class MyServletRequestListener implements ServletRequestListener { public void requestDestroyed(ServletRequestEvent evt) { System.out.println("销毁request对象"); }
public void requestInitialized(ServletRequestEvent evt) { System.out.println("创建request对象"); } }
|
<listener> <listener-class>cn.itcast.listener.MyServletContextListener</listener-class> </listener> <listener> <listener-class>cn.itcast.listener.MyHttpSessionListener</listener-class> </listener> <listener> <listener-class>cn.itcast.listener.MyServletRequestListener</listener-class> </listener> <session-config> <session-timeout>1</session-timeout> </session-config> |