Day08JavaWeb【Filter与Listener】Listener

listener overview

  • (1) What is a listener?
    Listener is used to monitor domain objects
  • (2) What is a domain object?
    HttpServletContext HtttpSession HttpRequest HttpPageContext
  • (3) Analogy, the head
    teacher monitors the status of students
  • (4) What are the listeners?
    Listener monitors the creation and destruction of
    domain objects
  • (5) What are the characteristics
    "1 No listening address
    " 2 Different objects use different listeners
    Insert picture description here

Use of listener

  • (1) Idea creates a listener
  • (2) Analog Servlet and 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域销毁啦");
    }

}

Guess you like

Origin blog.csdn.net/u013621398/article/details/108589359