1 基本概念java
监听器是一个专门用于对其余对象身上发生的事件或状态改变进行监听和相应处理的对象,当被监视的对象发生状况时,当即采起相应的行动。监听器其实就是一个实现特定接口的普通java程序,这个程序专门用于监听另外一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法当即被执行。web
JavaWeb中的监听器是Servlet规范中定义的一种特殊类,它用于监听web应用程序中的ServletContext,HttpSession和ServletRequest等域对象的建立于销毁时间,以及监听这些域对象中的属性发生修改的事件。服务器
2 Servlet监听器的分类app
在Servlet规范中定义了多种类型的监听器,它们用于监听的事件源分别为ServletletContext、HttpSession和ServletRequest这三个域对象。ide
Servlet规范针对这三个对象上的操做,又把多种类型的监听器划分为三种类型:xml
● 监听域对象自身的建立和销毁的事件监听器。对象
● 监听域对象中的属性的增长和删除的事件监听器。接口
● 监听绑定到HttpSession域中的某个对象的状态的事件监听器。事件
3 监听ServletContext域对象的建立和销毁ip
ServletContextListener接口用于监听ServletContext对象的建立和销毁事件。实现了ServletContextListener接口的类均可以对ServletContext对象的建立和销毁进行监听。
当ServletContext对象被建立时,激发contextInitialized(ServletContextEvent event)方法。
当ServletContext对象被销毁时,激发contextDestoryed(ServletContextEvent event)方法。
ServletContext域对象建立和销毁时机:
建立:服务器启动针对每个Web应用建立ServletContext。
销毁:服务器关闭前先关闭表明每个Web应用的ServletContext。
范例:编写一个MyServletContextListener类,实现ServletContextListener接口,监听ServletContext对象的建立和销毁。
● 编写监听器,代码以下:
package com.xdl.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* MyServletContextListener类实现了ServletContextListener接口
* 所以能够对ServletContext对象的建立和销毁这两个动做进行监听
*/
public class MyServletContextListener implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("ServletContext对象建立");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContext对象销毁");
}
}
● 在web.xml文件中注册监听器
● 咱们在上面中讲到,要想监听事件源,那么必须将监听器注册到事件源上才可以实现对事件源的行为动做进行监听,在JavaWeb中,监听的注册时在web.xml文件中进行配置的。详细配置以下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<listener>
<description>ServletContextListener监听器</description>
<listener-class>com.xdl.listener.MyServletContextListener</listener-class>
</listener>
</web-app>
通过这两个步骤,咱们就完成了监听器的编写和注册,Web服务器在启动时,就会自动把在web.xml文件中配置的监听器注册到ServletContext对象上,这样开发好的MyServletContextListener监听器就能够对ServletContext对象进行监听了。