Java-監聽器,java監聽器例子

來源:互聯網
上載者:User

Java-監聽器,java監聽器例子

監聽器也叫Listener,是Servlet的監聽器,它可以監聽用戶端的請求、服務端的操作等。通過監聽器,可以自動激發一些操作,比如監聽線上的使用者的數量。

例:ServletContextListener監聽ServletContext對象。

建立一個web項目

建立CountUtils和ListenerTest類並編寫代碼

配置web.xml

編寫jsp頁面

運行代碼並訪問(兩個人同時訪問)

 

常用的監聽介面:

  ServletContextAttributeListener監聽對ServletContext屬性的操作,比如增加、刪除、修改屬性。 

  ServletContextListener監聽ServletContext對象。

  當建立ServletContext時,激發contextInitialized(ServletContextEvent   sce)方法;

  當銷毀ServletContext時,激發contextDestroyed(ServletContextEvent   sce)方法。

 

HttpSessionListener監聽HttpSession的操作:

  當建立一個Session時,激發sessionCreated(HttpSessionEvent   se)方法;

  當銷毀一個Session時,激發sessionDestroyed(HttpSessionEvent   se)方法。 

HttpSessionAttributeListener監聽HttpSession中的屬性的操作:

  當在Session增加一個屬性時,激發attributeAdded(HttpSessionBindingEvent  se)方法;

  當在Session刪除一個屬性時,激發attributeRemoved(HttpSessionBindingEvent   se)方法;

  當在Session屬性被重新設定時,激發attributeReplaced(HttpSessionBindingEvent   se)   方法。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.