【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 中国大陆许可协议进行许可。

posted @   喝着农药吐泡泡o  阅读(107)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
🔑