什么是Listener监听器
| 1、Listener监听器它是JavaWeb的三大组件之一。 |
| JavaWeb的三大组件分别是:Servlet程序、Filter过滤器、Listener监听器。 |
| |
| 2、Listener它是JavaEE的规范,就是接口 |
| |
| 3、监听器的作用是,监听某种事物的变化。然后通过回调函数,反馈给客户(程序)去做一些相应的处理。 |
1.ServletContextListener监听器
| ServletContextListener它可以监听ServletContext对象的创建和销毁。 |
| |
| ServletContext对象在web工程启动的时候创建,在web工程停止的时候销毁。 |
| |
| 监听到创建和销毁之后都会分别调用ServletContextListener监听器的方法反馈。 |
两个方法分别是:
| public interface ServletContextListener extends EventListener{ |
| |
| |
| |
| public void contextInitialized(ServletContextEvent sce); |
| |
| |
| |
| public void contextDestroyed(ServletContextEvent sce); |
| } |
| 如何使用ServletContextListener监听器监听ServletContext对象。 |
| 使用步骤如下: |
| 1、编写一个类去实现ServletContextListener |
| 2、实现其两个回调方法 |
| 3、到web.xml中去配置监听器 |
监听器实现类:
| public class MyServletContextListenerImpl 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.atguigu.listener.MyServletContextListenerImpl</listener-class> |
| </listener> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步