日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Listener 监听器

發布時間:2025/7/25 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Listener 监听器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

Listener 監聽器

?

  前言:之前寫了一篇關于Filter的文章:http://tianweili.github.io/blog/2015/01/26/java-filter/,現在再來一篇Listener的,Filter和Listener在項目中是經常用到的,巧妙的使用可以達到事半功倍的效果。故把兩者的用法總結一下。

  原文鏈接:http://tianweili.github.io/blog/2015/01/27/java-listener/

1、Listener的定義與作用

  監聽器Listener就是在application,session,request三個對象創建、銷毀或者往其中添加修改刪除屬性時自動執行代碼的功能組件。

  Listener是Servlet的監聽器,可以監聽客戶端的請求,服務端的操作等。

2、Listener的分類與使用

  主要有以下三類:

  1、ServletContext監聽

  ServletContextListener:用于對Servlet整個上下文進行監聽(創建、銷毀)。

public void contextInitialized(ServletContextEvent sce);//上下文初始化 public void contextDestroyed(ServletContextEvent sce);//上下文銷毀public ServletContext getServletContext();//ServletContextEvent事件:取得一個ServletContext(application)對象

  ServletContextAttributeListener:對Servlet上下文屬性的監聽(增刪改屬性)。

public void attributeAdded(ServletContextAttributeEvent scab);//增加屬性 public void attributeRemoved(ServletContextAttributeEvent scab);//屬性刪除 public void attributeRepalced(ServletContextAttributeEvent scab);//屬性替換(第二次設置同一屬性)//ServletContextAttributeEvent事件:能取得設置屬性的名稱與內容 public String getName();//得到屬性名稱 public Object getValue();//取得屬性的值

  2、Session監聽

  Session屬于http協議下的內容,接口位于javax.servlet.http.*包下。

  HttpSessionListener接口:對Session的整體狀態的監聽。

public void sessionCreated(HttpSessionEvent se);//session創建 public void sessionDestroyed(HttpSessionEvent se);//session銷毀//HttpSessionEvent事件: public HttpSession getSession();//取得當前操作的session

  HttpSessionAttributeListener接口:對session的屬性監聽。

public void attributeAdded(HttpSessionBindingEvent se);//增加屬性 public void attributeRemoved(HttpSessionBindingEvent se);//刪除屬性 public void attributeReplaced(HttpSessionBindingEvent se);//替換屬性//HttpSessionBindingEvent事件: public String getName();//取得屬性的名稱 public Object getValue();//取得屬性的值 public HttpSession getSession();//取得當前的session

  session的銷毀有兩種情況:

  1、session超時,web.xml配置:

<session-config><session-timeout>120</session-timeout><!--session120分鐘后超時銷毀--> </session-config>

  2、手工使session失效

public void invalidate();//使session失效方法。session.invalidate();

  3、Request監聽

  ServletRequestListener:用于對Request請求進行監聽(創建、銷毀)。

public void requestInitialized(ServletRequestEvent sre);//request初始化 public void requestDestroyed(ServletRequestEvent sre);//request銷毀//ServletRequestEvent事件: public ServletRequest getServletRequest();//取得一個ServletRequest對象 public ServletContext getServletContext();//取得一個ServletContext(application)對象

  ServletRequestAttributeListener:對Request屬性的監聽(增刪改屬性)。

public void attributeAdded(ServletRequestAttributeEvent srae);//增加屬性 public void attributeRemoved(ServletRequestAttributeEvent srae);//屬性刪除 public void attributeReplaced(ServletRequestAttributeEvent srae);//屬性替換(第二次設置同一屬性)//ServletRequestAttributeEvent事件:能取得設置屬性的名稱與內容 public String getName();//得到屬性名稱 public Object getValue();//取得屬性的值

  4、在web.xml中配置

  Listener配置信息必須在Filter和Servlet配置之前,Listener的初始化(ServletContentListener初始化)比Servlet和Filter都優先,而銷毀比Servlet和Filter都慢。

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

3、Listener應用實例

  1、利用HttpSessionListener統計最多在線用戶人數

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener;public class HttpSessionListenerImpl implements HttpSessionListener {public void sessionCreated(HttpSessionEvent event) {ServletContext app = event.getSession().getServletContext();int count = Integer.parseInt(app.getAttribute("onLineCount").toString());count++;app.setAttribute("onLineCount", count);int maxOnLineCount = Integer.parseInt(app.getAttribute("maxOnLineCount").toString());if (count > maxOnLineCount) {//記錄最多人數是多少app.setAttribute("maxOnLineCount", count);DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//記錄在那個時刻達到上限app.setAttribute("date", df.format(new Date()));}}//session注銷、超時時候調用,停止tomcat不會調用public void sessionDestroyed(HttpSessionEvent event) {ServletContext app = event.getSession().getServletContext();int count = Integer.parseInt(app.getAttribute("onLineCount").toString());count--;app.setAttribute("onLineCount", count); } }

  2、Spring使用ContextLoaderListener加載ApplicationContext配置信息

  ContextLoaderListener的作用就是啟動Web容器時,自動裝配ApplicationContext的配置信息。因為它實現了ServletContextListener這個接口,在web.xml配置這個監聽器,啟動容器時,就會默認執行它實現的方法。

  ContextLoaderListener如何查找ApplicationContext.xml的配置位置以及配置多個xml:如果在web.xml中不寫任何參數配置信息,默認的路徑是"/WEB-INF/applicationContext.xml",在WEB-INF目錄下創建的xml文件的名稱必須是applicationContext.xml(在MyEclipse中把xml文件放置在src目錄下)。如果是要自定義文件名可以在web.xml里加入contextConfigLocation這個context參數。

<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/applicationContext-*.xml</param-value><!-- 采用的是通配符方式,查找WEB-INF/spring目錄下xml文件。如有多個xml文件,以“,”分隔。 --> </context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>

  3、Spring使用Log4jConfigListener配置Log4j日志

  Spring使用Log4jConfigListener的好處:

  • 動態的改變記錄級別和策略,不需要重啟Web應用。
  • 把log文件定在 /WEB-INF/logs/ 而不需要寫絕對路徑。因為系統把web目錄的路徑壓入一個叫webapp.root的系統變量。這樣寫log文件路徑時不用寫絕對路徑了。
  • 可以把log4j.properties和其他properties一起放在/WEB-INF/ ,而不是Class-Path。
  • 設置log4jRefreshInterval時間,開一條watchdog線程每隔段時間掃描一下配置文件的變化。
  • <context-param><param-name>webAppRootKey</param-name><param-value>project.root</param-value><!-- 用于定位log文件輸出位置在web應用根目錄下,log4j配置文件中寫輸出位置:log4j.appender.FILE.File=${project.root}/logs/project.log --> </context-param> <context-param><param-name>log4jConfigLocation</param-name><param-value>classpath:log4j.properties</param-value><!-- 載入log4j配置文件 --> </context-param> <context-param><param-name>log4jRefreshInterval</param-name><param-value>60000</param-value><!--Spring刷新Log4j配置文件的間隔60秒,單位為millisecond--> </context-param><listener><listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>

      4、Spring使用IntrospectorCleanupListener清理緩存

      這個監聽器的作用是在web應用關閉時刷新JDK的JavaBeans的Introspector緩存,以確保Web應用程序的類加載器以及其加載的類正確的釋放資源。

      如果JavaBeans的Introspector已被用來分析應用程序類,系統級的Introspector緩存將持有這些類的一個硬引用。因此,這些類和Web應用程序的類加載器在Web應用程序關閉時將不會被垃圾收集器回收!而IntrospectorCleanupListener則會對其進行適當的清理,已使其能夠被垃圾收集器回收。

      唯一能夠清理Introspector的方法是刷新整個Introspector緩存,沒有其他辦法來確切指定應用程序所引用的類。這將刪除所有其他應用程序在服務器的緩存的Introspector結果。

      在使用Spring內部的bean機制時,不需要使用此監聽器,因為Spring自己的introspection results cache將會立即刷新被分析過的JavaBeans Introspector cache,而僅僅會在應用程序自己的ClassLoader里面持有一個cache。雖然Spring本身不產生泄漏,注意,即使在Spring框架的類本身駐留在一個“共同”類加載器(如系統的ClassLoader)的情況下,也仍然應該使用使用IntrospectorCleanupListener。在這種情況下,這個IntrospectorCleanupListener將會妥善清理Spring的introspection cache。

      應用程序類,幾乎不需要直接使用JavaBeans Introspector,所以,通常都不是Introspector resource造成內存泄露。相反,許多庫和框架,不清理Introspector,例如: Struts和Quartz。

      需要注意的是一個簡單Introspector泄漏將會導致整個Web應用程序的類加載器不會被回收!這樣做的結果,將會是在web應用程序關閉時,該應用程序所有的靜態類資源(比如:單實例對象)都沒有得到釋放。而導致內存泄露的根本原因其實并不是這些未被回收的類!

      注意:IntrospectorCleanupListener應該注冊為web.xml中的第一個Listener,在任何其他Listener之前注冊,比如在Spring's ContextLoaderListener注冊之前,才能確保IntrospectorCleanupListener在Web應用的生命周期適當時機生效。

    <!-- memory clean --> <listener><listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener>

    ?原文鏈接:http://tianweili.github.io/blog/2015/01/27/java-listener/

    轉載于:https://www.cnblogs.com/hellojava/archive/2012/12/26/2833840.html

    總結

    以上是生活随笔為你收集整理的Listener 监听器的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。