天天看點

Listener監聽器_hehe.employment.over.19.419.9 Listener_概述19.10 Listener_使用步驟

文章目錄

  • 19.9 Listener_概述
  • 19.10 Listener_使用步驟

19.9 Listener_概述

  • Listener: 監聽器,web的三大元件之一。
    • 事件監聽機制
      • 事件 :一件事情
      • 事件源 :事件發生的地方
      • 監聽器 :一個對象
      • 注冊監聽 :将事件、事件源、監聽器綁定在一起。 當事件源上發生某個事件後,執行監聽器代碼
  • ServletContextListener : 監聽ServletContext對象的建立和銷毀
    • 方法:
      • void contextDestroyed(ServletContextEvent sce)

        :ServletContext對象被銷毀之前會調用該方法.
      • void contextInitialized(ServletContextEvent sce)

        :ServletContext對象建立後會調用該方法.

19.10 Listener_使用步驟

  • 使用步驟:
    • 1.定義一個類,實作ServletContextListener接口;
    • 2.複寫方法;
    • 3.配置
      • web.xml ;
      • 2注解:

        @WebListener

  • 示例:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
   <!--
   配置監聽器
-->
   <listener>
      <listener-class>com.xww.web.listener.ContextLoaderListener</listener-class>
   </listener>

   <!-- 指定初始化參數 -->
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
   </context-param>
   
</web-app>

           
package com.xww.web.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.FileInputStream;


@WebListener//注解
public class ContextLoaderListener implements ServletContextListener {

    /**
     * 監聽ServletContext對象建立的。ServletContext對象伺服器啟動後自動建立。
     *
     * 在伺服器啟動後自動調用
     * @param servletContextEvent
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //加載資源檔案
        //1.擷取ServletContext對象
        ServletContext servletContext = servletContextEvent.getServletContext();

        //2.加載資源檔案
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");

        //3.擷取真實路徑
        String realPath = servletContext.getRealPath(contextConfigLocation);

        //4.加載進記憶體
        try{
            FileInputStream fis = new FileInputStream(realPath);
            System.out.println(fis);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("ServletContext對象被建立了。。。");
    }

    /**
     * 在伺服器關閉後,ServletContext對象被銷毀。當伺服器正常關閉後該方法被調用
     * @param servletContextEvent
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("ServletContext對象被銷毀了。。。");
    }
}