Java ---Listener監聽器

在我們的web容器中,一直不斷的觸發著各種事件,例如:web應用啟動和關閉,request請求到達和結束等。但是這些事件通常對于開發者來說是透明的,我們可以根據這些接口開發符合我們自身需求的功能。在web中常見的的幾個監聽事件如下:

  • ServletContextListener:用于監聽web應用的啟動和關閉
  • ServletContextAttributeListener:用于監聽在application范圍內的數據的變動
  • ServletRequestListener:用于監聽用戶請求的細節
  • ServletRequestAttributeListener:用于監聽request范圍內的數據的變動
  • HttpSessionListener:用于監聽某次會話的開始和結束
  • HttpSessionAttributeListener:用于監聽session范圍內的屬性數據的變動

一、使用ServletContextListener監聽web應用的啟動和關閉
我們想要實現一個自定義的Listener,需要兩個步驟,第一個是根據自己的需求繼承相應的上述的監聽事件的接口,并實現其中的相應的方法。第二個步驟就是,在web.xml中配置此Listener監聽器的處理類或者使用注解配置。下面我們通過繼承自ServletContextListener接口來實現對web應用的啟動和關閉實時監控。

public class MyListener implements ServletContextListener {

    @Override//web應用啟動時候觸發此事件
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("web應用啟動了。。。");
    }

    @Override//web應用關閉的時候觸發事件
    public void contextDestroyed(ServletContextEvent sce) {

        System.out.println("web應用被關閉了。。。");
    }

}
<?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>Test_packge.MyListener</listener-class>
    </listener>
</web-app>
1.png

二、使用ServletContextAttributeListener監聽application范圍內的屬性變化
上面的代碼可以讓我們監聽web應用的啟動和關閉情況,下面我們可以通過實現ServletContextAttributeListener接口來完成對application范圍內的屬性數值改變情況進行監聽。其中主要有以下三個方法:


    default void attributeAdded(ServletContextAttributeEvent scae) {
    }

    default void attributeRemoved(ServletContextAttributeEvent scae) {
    }

    default void attributeReplaced(ServletContextAttributeEvent scae) {
    }

這三個方法分別會在application范圍內添加屬性的時候,刪除屬性的時候,更新屬性的時候觸發。下面做一點演示:

public class MyListener implements ServletContextAttributeListener {

    @Override
    public void attributeAdded(ServletContextAttributeEvent scae) {

        String name = scae.getName();
        Object value = scae.getValue();
        System.out.println("add: "+name+":"+value);
    }
    @Override
    public void attributeRemoved(ServletContextAttributeEvent scae) {

        String name = scae.getName();
        Object value = scae.getValue();
        System.out.println("remove: "+name+":"+value);
    }
    @Override
    public void attributeReplaced(ServletContextAttributeEvent scae) {

        String name = scae.getName();
        Object value = scae.getValue();
        System.out.println("replaced: "+name+":"+value);
    }
}
<%application.setAttribute("x","a");%>

<%application.removeAttribute("x","a");%>

上述代碼中,我們調用了ServletContextAttributeEvent 對象的getName方法和getValue方法來獲取當前的application屬性的名和值。當然此對象還有另外一個方法就是用于獲取servlecontext對象的。

三、使用ServletRequestListener監聽用戶請求的開始和結束
上述代碼主要完成的是對web應用的啟動和結束的狀態進行監聽,包括application范圍內的屬性值的改變的監聽。下面我們看對用戶請求進行監聽的接口ServletRequestListener,它主要有兩個方法:

    default void requestDestroyed(ServletRequestEvent sre) {
    }

    default void requestInitialized(ServletRequestEvent sre) {
    }

這兩個方法分別會在請求的到達和請求的結束時觸發,ServletRequestEvent 中定義的方法可以返回當前請求的對象request和web應用的ServletContext對象。通過繼承接口ServletRequestAttributeListener可以實現監聽request范圍內的屬性的變更,其內部方法和上述的ServletContextAttributeListener 類似,不演示了。

四、使用HttpSessionListener監聽會話的開始和結束
HttpSessionListener監聽器用于監聽每個用戶創建會話和關閉會話的動作,有兩個方法:

    default void sessionCreated(HttpSessionEvent se) {
    }

    default void sessionDestroyed(HttpSessionEvent se) {
    }

一個是用于監聽會話開始,一個是用于監聽會話的結束。HttpSessionEvent 類可以返回一HttpSession對象,該對象指向當前會話,可以從中獲取會話創建的時間,屬性值,sessionId,ServletContext對象等。通過他我們可以直接的監視具體用戶的各個操作。下面我們通過一個例子:顯示當前所有在線的用戶

public class MyListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent se) {

        ServletContext app = se.getSession().getServletContext();
        //如果是新一次會話
        if(se.getSession().isNew()){
            Map<String,String> map = (Map<String,String>)app.getAttribute("online");
            if(map==null){
                //如果這是第一次會話,創建一個用于記錄在線人數的map集合
                map = new Hashtable<String, String>();
            }
            //此處的用戶名實際上是可以獲取的,此處為了演示方便,默認walekr
            map.put(se.getSession().getId(),"walker");
            app.setAttribute("online",map);
        }
    }
    public void sessionDestroyed(HttpSessionEvent se) {

        ServletContext app = se.getSession().getServletContext();
        Map<String,String> map = (Map<String,String>)app.getAttribute("online");
        if(map!=null) {
            map.remove(se.getSession().getId());
        }
        app.setAttribute("online",map);
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>
      <%
        Map<String,String> map = (Map<String,String>)application.getAttribute("online");
        for(String key : map.keySet()){
      %>
      <p><%=key%>:<%=map.get(key)%></p>
    <%}%>
  </body>
</html>
2.png

做一點解釋,當用戶使用瀏覽器訪問服務器時候,會為此用戶創建session對象,我們監聽創建session動作,在application范圍內創建map映射集合用于記錄sessionId和用戶名,sessionId是web容器為我們自動創建的不會重復的序列。我們可以打開多個瀏覽器模擬多用戶訪問,可以看到結果如上圖所示,輸出了所有與在線的用戶sessionId和用戶名。需要注意一點的是,session對象在服務器端存在的是時間是有限的,也就是說如果某個用戶長時間沒有再次訪問服務器更新session的話,服務器會自動清除該對象,也就導致用戶可能需要重新登錄。還有一點,每個客戶端都會獲取在服務器端的session對象,但是如果客戶端關閉了,session并不會立即從服務器端清除,依然需要等到超時之后服務器刪除該對象。具體的深入理解session,以后的文章會介紹,此處了解即可。

此外,HttpSessionAttributeListener可以用來監聽session范圍內的屬性的變更,主要有如下幾個方法:

    default void attributeAdded(HttpSessionBindingEvent se) {
    }

    default void attributeRemoved(HttpSessionBindingEvent se) {
    }

    default void attributeReplaced(HttpSessionBindingEvent se) {
    }

這三個方法和上述的幾個監聽屬性的方法是類似的,此處不再贅述。

以上便是Listener監聽器的基本內容,理解較為淺薄,望對大家有幫助!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,971評論 6 342
  • 從三月份找實習到現在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發崗...
    時芥藍閱讀 42,373評論 11 349
  • 轉自:http://blog.csdn.net/jackfrued/article/details/4493113...
    王帥199207閱讀 2,476評論 2 19
  • 央視曾經做過這樣的采訪:你幸福嗎?我姓朱這樣的回答也讓這個調查變成了一個笑話。這樣一想,世上除了最近變成表情包的爾...
    屁桃醬的文藝生活閱讀 202評論 1 0