. 监听器概述
1 .Listener是Servlet的监听器
. 2 .可以监听客户端的请求、服务端的操作等。
. 3 .通过监听器,可以自动激发一些操作,如监听在线用户数量,当增加一个HttpSession时,给在线人数加 1 。
. 4 .编写监听器需要实现相应的接口
. 5 .编写完成后在web.xml文件中配置一下,就可以起作用了
. 6 .可以在不修改现有系统基础上,增加web应用程序生命周期事件的跟踪
常用的监听接口
. 1 .ServletContextAttributeListener 监听对ServletContext属性的操作,比如增加/删除/修改
. 2 .ServletContextListener 监听ServletContext,当创建ServletContext时,激发 contextInitialized(ServletContextEvent sce)方法;当销毁ServletContext时,激发 contextDestroyed(ServletContextEvent sce)方法。 3 .HttpSessionListener 监听HttpSession的操作。当创建一个Session时,激发session Created(SessionEvent se)方法;当销毁一个 Session时,激发sessionDestroyed (HttpSessionEvent se)方法。 4 .HttpSessionAttributeListener 监听HttpSession中的属性的操作。当在Session增加一个属性时,激发 attributeAdded(HttpSessionBindingEvent se) 方法;当在Session删除一个属性时,激发 attributeRemoved(HttpSessionBindingEvent se)方法;当在Session属性被重新设置时,激发 attributeReplaced(HttpSessionBindingEvent se) 方法。
下面是2个列子,一个是监听人数,一个是定时器监听。