Day08JavaWeb【Filter与Listener】Listener

listener概述

  • (1)什么是监听器?
    Listener是用来监听域对象
  • (2)什么是域对象?
    HttpServletContext HtttpSession HttpRequest HttpPageContext
  • (3)类比
    班主任监听同学的状态
  • (4)监听器有哪些?
    Listener监听域对象创建和销毁 生死
    Listener监听域对象属性的变化 变化
  • (5)有什么特点
    》1 没有监听地址
    》2 不同的对象使用不同的监听器
    在这里插入图片描述

listener的使用

  • (1)idea创建监听器
  • (2)类比 Servlet与Filter

src\com.wzx.pack06_listener\TestDemo.java

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        Timer timer = new Timer();

        timer.schedule(new TimerTask() {
    
    
            @Override
            public void run() {
    
    
                System.out.println("时间到了");
            }
        }, 5000,2000);  //5秒之后执行run方法,每隔2秒再执行 run方法
    }
}

src\com.wzx.pack06_listener\Demo1Listener.java

@WebListener()
public class Demo1Listener implements ServletContextListener{
    
    

    public Demo1Listener() {
    
    
    }

    //这个方法用来监听ServletContext域的创建
    /*
        这个域:服务器启动时创建
     */
    public void contextInitialized(ServletContextEvent sce) {
    
    
        //设置一个定时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
    
    
            @Override
            public void run() {
    
    
                try {
    
    
                    System.out.println("--定时发送邮件");
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
        }, 5000, 2000);
        System.out.println("ServletContext域的创建啦");
    }

    //这个方法用来监听ServletContext域的销毁
    /*
       这个域:服务器关闭时销毁
     */
    public void contextDestroyed(ServletContextEvent sce) {
    
    
        System.out.println("ServletContext域销毁啦");
    }

}

猜你喜欢

转载自blog.csdn.net/u013621398/article/details/108589359