【Javaweb】什么是Listener监听器?
1、Listener监听器它是Javaweb的三大组件之一。Javaweb的三大组件分别是:Servelt程序,Filter过滤器,Listener监听器。
2、Listener它是JavaEE的规范,就是接口
3、监听器的作用是,监听某种事物的变化。然后通过回调函数,反馈给客户(程序)去做一些相应的处理。
ServletContextListener监听器
ServletContextListener 它可以监听ServletContext对象的创建和销毁。
ServletContext 对象在web工程启动的时候创建,在web工程停止的时候销毁。
监听到创建和销毁之后都会分别调用ServletContextListener 监听器的方法反馈。
两个方法
分别是:
public interface ServletContextListener extends EventListener { default void contextInitialized(ServletContextEvent sce) { /** *在ServletContext对象创建之后马上调用,做初始化 */ } default void contextDestroyed(ServletContextEvent sce) { /** *在ServletContext对象销毁之后调用 */ } }
如何使用ServletContextListener 监听器监听 ServletContext 对象
使用步骤如下:
1、编写一个类去实现ServletContextListener
2、实现其两个回调方法
3、到web.xml中去配置监听器
public class MyServletContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("ServletContextListener被创建了!!!"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("ServletContextListener被销毁了!!!"); } }
本文作者:TranquilTimber
本文链接:https://www.cnblogs.com/gbrr/p/17081328.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步