一、什么是监听器、它有什么作用
listener监听器是javaWeb的三大组件之一。另外两大组件是servlet、filter。
listener是Java EE的规范,也就是接口
监听器的作用:
监听某种事物的变化,然后回调函数,反馈给程序,做对应的处理。
二、ServletContextListener监听器及其实现方式
1.ServletContextListener:可以监听ServletContext对象的创建和销毁。
ServletContext 对象在web工程启动的时候创建,在web工程停止的时候销毁。
监听到创建和销毁时都会分别调用servletContextListener的两个方法。
public interface ServletContextListener extends EventListener {
//servletContext对象创建后调用
default public void contextInitialized(ServletContextEvent sce) {}
//servletContext对象销毁后调用
default public void contextDestroyed(ServletContextEvent sce) {}
}
2.实现方式:
(1)编写一个类实现servletContextListener;
(2)实现其两个回调方法;
(3)在web.xml中进行配置。
测试类:
public class MyServletListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContext对象被创建了");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("ServletContext对象被销毁了");
}
}
web.xml配置:
<listener>
<listener-class>com.wq.listener.MyServletListener</listener-class>
</listener>