一、Listener介绍
Listener中文名为监听器,通过它可以监听容器中的某一执行动作,并根据要求做出相应的响应。主要的8个Listener借口可分为三类:
(1)与ServletContext有关的Listener接口:ServletContextListener, ServletContextAttributeListener;
(2)与HttpSession有关的Listener的接口:HttpSessionListener, HttpSessionAttributeListener, HttpSessionBindingListener, HttpSessionActivationListener;
(3)与ServletRequest有关的Listener接口:ServletRequestListener, ServletRequestAttributeListener 。
二、Listener的配置
在web.xml文件中,通过如下方式配置一个Listener接口:
<listener>
<listener-class>Java类名</listener-class>
</listener>
三、重点Listener介绍
1. ServletContextListener
该接口用来实现ServletContext的启动和销毁监听。它包含两个方法:
(1)contextInitialized(ServletContextEvent sce)方法,用来监听ServletContext的启动和初始化(web应用启动时调用);
(2)contextDestroyed(ServletContextEvent sce)方法,用来监听ServletContext的销毁(web应用停止时调用)。
在方法内部,可以通过ServletContextEvent对象的getServletContext()方法获得ServletContext对象。
2. ServletContextAttributeListener
该接口用来实现application范围属性变化的监听。它包含三个方法:
(1)attributeAdded(ServletContextAttributeEvent scab),用来监听application范围属性的添加;
(2)attributeReplaced(ServletContextAttributeEvent scab),用来监听application范围属性的替换;
(3)attributeRemoved(ServletContextAttributeEvent scab),用来监听application范围属性的移除;
以上三个方法都可以通过scab.getName()可以获得属性名,通过scab.getValue()可以获得属性值。
3. HttpSessionListener
该接口用来实现session的初始化和销毁监听,可以用来收集在线者信息。其中包含两个方法,在这两个方法中都可以通过se.getSession()来获得HttpSession类的一个对象session(HttpSession session=se.getSession()):
(1)sessionCreated(HttpSessionEvent se),该方法在创建Session时被执行,可以通过session.getId()来获得session的ID;
(2)sessionDestroyed(HttpSessionEvent se),该方法在超时或者主动调用session.invalidate()时执行。
4. HttpSessionAttribution
该接口用来实现session范围属性变化的监听。该接口有三个方法:
(1)attributeAdded(HttpSessionBindingEvent se),用来监听application范围属性的添加;
(2)attributeReplaced(HttpSessionBindingEvent se),用来监听application范围属性的替换;
(3)attributeRemoved(HttpSessionBindingEvent se),用来监听application范围属性的移除;
以上三个方法都可以通过se.getName()可以获得属性名,通过se.getValue()可以获得属性值。
5. HttpSessionActivationListener
该接口用来实现session范围属性变化的监听。服务器关闭时,会将session里的内容保存到硬盘上,这个过程叫钝化;服务器重新启动时,会将session的内容从硬盘上重新加载,这个过程叫活化。值得一提的是,实现此接口的JavaBean与HttpSessionBindingListener一样,不必配置到web.xml中。实现HttpSessionActivationListener接口的JavaBean可以感知自己被钝化和被活化,该接口有两个方法:
(1)sessionWillPassive(HttpSessionEvent se):监听session里实现该接口的类对象的钝化;
(2)sessionDidActivate(HttpSessionEvent se):监听session里实现该接口的类对象的活化。