1.监听器简介:
监听器主要用来监听对象的创建,属性的变化,是一个实现特定接口的普通Java类。
Listener接口与事件对应表:
与 ServletContext 有关 |
ServletContextListener |
ServletContextEvent |
ServletContextAttributeListener |
ServletContextAttributeEvent |
与 HttpSession 有关 |
HttpSessionListener |
HttpSessionEvent |
HttpSessionActivationListener |
HttpSessionAttributeListener |
HttpSessionBindingEvent |
HttpSessionBindingListener |
与 ServletRequest 有关 |
ServletRequestListener |
ServletRequestEvent |
ServletRequestAttributeListener |
ServletRequestAttributeEvent |
编写监听器的步骤:
编写实现类->在web.xml中进行部署->编写测试页面
2.与ServletContext相关监听器
单个Web站点的资源都共享一个javax.servlet.ServletContext类的实体。通过该对象可以存取应用程序的全局对象以及初始化阶段的变量
全局对象即为Application范围对象,其生命周期从容器启动至容器关闭。初始阶段的变量是指在web.xml中,由<context-param>元素设定的变量,该变量的范围是Application范围
ServletContextListener接口:
实现了该接口的程序,当JavaWeb应用程序启动时,会自动开始监听工作
首先调用contextInitialized()方法接收对应的ServletContextEvent事件
当应用从容器中移除时,会自动调用contextDestroyed()方法
以上两个方法都会接收到ServletContextEvent事件对象,该对象可以调用getServletContext()方法取得ServletContext对象(全局对象)
ServletContextAttributeListener接口:
实现该接口的程序,能够监听ServletContext属性的变化,例如:当往ServletContext中添加数据时,该程序会被调用。
方法 |
说明 |
attributeAdded(ServletContextAttributeEvent e) |
若有对象加入Application范围时,通知 正在收听的对象 |
attributeReplaced(ServletContextAttributeEvent e) |
若在Application的范围,有对象取代另 |