一、簡介
Java的監聽器,也是系統級别的監聽。監聽器随web應用的啟動而啟動。Java的監聽器在c/s模式裡面經常用到,它會對特定的事件産生産生一個處理。監聽在很多模式下用到,比如說觀察者模式,就是一個使用監聽器來實作的,在比如統計網站的線上人數。
1.1 監聽器分類
1) 按監聽的對象劃分,可以分為:
ServletContext對象監聽器
HttpSession對象監聽器
ServletRequest對象監聽器
2)按監聽的事件劃分
對象自身的建立和銷毀的監聽器
對象中屬性的建立和消除的監聽器
session中的某個對象的狀态變化的監聽器
二、适用場景
springMVC監聽器主要的作用就是spring容器啟動的時候加載一些資料,最常用的功能就是開發權限系統的時候,當監聽器啟動的時候,從資料庫加載權限url。
三、實作
一、ContextLoaderListener
ContextLoaderListener監聽器的作用就是啟動Web容器時,自動裝配ApplicationContext的配置資訊。因為它實作了ServletContextListener這個接口,web.xml配置這個監聽器啟動容器時,就會預設執行它實作的方法。在ContextLoader-Listener中關聯了ContextLoader這個類,是以整個加載配置過程由ContextLoader來完成。ContextLoader可以由 ContextLoaderListener和ContextLoaderServlet生成。檢視ContextLoaderServlet的API,它也關聯了ContextLoader這個類而且它實作了HttpServlet這個接口;ContextLoader建立的是XmlWebApplicationContext這樣一個類,實作的接口是WebApplicationContext->ConfigurableWebApplicationContext->ApplicationContext->BeanFactory。這樣一來spring中的所有bean都由這個類來建立。如果在web.xml中不寫任何參數配置資訊,預設的路徑是/WEB-INF/applicationContext.xml,在WEB-INF目錄下建立的xml檔案的名稱必須是applicationContext.xml;如果是要自定義檔案名可以在web.xml裡加入contextConfigLocation這個context參數:
contextConfigLocation
/WEB-INF/classes/applicationContext-*.xml
在裡指定相應的xml檔案名,如果有多個xml檔案,可以寫在一起并一“,”号分隔。上面的applicationContext-*.xml采用通配符,比如這那個目錄下有applicationContext-ibatis-base.xml,applicationContext-action.xml,applicationContext-ibatis-dao.xml等檔案,都會一同被載入。由此可見applicationContext.xml的檔案位置就可以有兩種預設實作:第一種:直接将之放到/WEB-INF下,之後在web.xml中聲明一個listener;第二種:将之放到classpath下,但是此時要在web.xml中加入,用它來指明你的applicationContext.xml的位置以供web容器來加載。按照Struts2 整合spring的官方給出的檔案,寫成:
contextConfigLocation
/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml
自定義監聽器的配置
1配置自定義的監聽器需要配置spring容器監聽器,因為自定期監聽器需要從spring容器中拿取資料,并且自定義監聽器的配置檔案位于spring監聽器之後
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
Device Manage Web Application
testFilter
com.my.dm.filter.TestFilter
demo
112.2.36
testFilter
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
DeviceService deviceService = ac.getBean(DeviceService.class);
logger.error("This is test for TestListener!");
logger.error(deviceService.getDeviceByNameIp("", "4.154.135.74").get(0));
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
}
參考:
https://www.jianshu.com/p/82ae825b849b
https://www.cnblogs.com/lukelook/p/11079113.html#t2