天天看點

JavaWeb初識監聽器

文章目錄

  • ​​簡要說明​​
  • ​​ServletContextListener 監聽器​​
  • ​​如何使用​​
  • ​​簡單示例​​
  • ​​監聽器配置​​
  • ​​Web.xml配置​​

簡要說明

1、Listener 監聽器它是 JavaWeb 的三大元件Servlet 程式、Filter 過濾器、Listener監聽器之一。

2、Listener 它是 JavaEE 的規範,就是接口。

3、監聽器的作用是,監聽某種事物的變化。然後通過回調函數,回報給客戶(程式)去做一些相應的處理。

ServletContextListener 監聽器

現在常用的監聽器便是ServletContextListener 監聽器,它可以監聽ServletContext 對象的建立和銷毀。

ServletContext 對象在 web 工程啟動的時候建立,在 web 工程停止的時候銷毀。

監聽到建立和銷毀之後都會分别調用 ServletContextListener 監聽器的方法回報。

如何使用

  • 1、編寫一個類去實作 ServletContextListener
  • 2、實作其兩個回調方法
  • 3、到 web.xml 中去配置監聽器

簡單示例

監聽器配置

public class MyServletContextListener implements ServletContextListener,
        HttpSessionListener, HttpSessionAttributeListener {

    // Public constructor is required by servlet spec
    public MyServletContextListener() {
    }

    public void contextInitialized(ServletContextEvent sce) {
      /* This method is called when the servlet context is
         initialized(when the Web application is deployed). 
         You can initialize servlet context related data here.
      */
        System.out.println("監聽器啟動");
    }

    public void contextDestroyed(ServletContextEvent sce) {
      /* This method is invoked when the Servlet Context 
         (the Web application) is undeployed or 
         Application Server shuts down.
      */
        System.out.println("監聽器銷毀");
    }
}      

Web.xml配置

<listener>
        <listener-class>com.stackery.listener.MyServletContextListener</listener-class>
</listener>