Java Web監(jiān)聽器Listener接口原理及用法實例
監(jiān)聽器主要針對三個對象
ServletContext HttpSession ServletRequest使用方式
創(chuàng)建*Listener接口的實現(xiàn)類 在web.xml中注冊該類在同時注冊多個同接口的監(jiān)聽器時,執(zhí)行順序參照web.xml中的注冊順序
監(jiān)聽器監(jiān)聽類型 對象的創(chuàng)建和銷毀 對象屬性的添加、替換、移除創(chuàng)建實現(xiàn)類
// 用于監(jiān)聽session創(chuàng)建和銷毀的監(jiān)聽器package listener;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;public class SessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent httpSessionEvent) { // 獲取本次事件創(chuàng)建session的id String sessionId = httpSessionEvent.getSession().getId(); System.out.println('create session that id = ' + sessionId); } @Override public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { // 刪除session的id String sessionId = httpSessionEvent.getSession().getId(); System.out.println('session has been destroy that id = ' + sessionId); }}
在web.xml中注冊
<?xml version='1.0' encoding='UTF-8'?><web-app xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://xmlns.jcp.org/xml/ns/javaee' xsi:schemaLocation='http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd' version='3.1'> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <listener> <!-- 在listener包下的SessionListener類 --> <listener-class>listener.SessionListener</listener-class> </listener></web-app>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例2. 用xslt+css讓RSS顯示的跟網(wǎng)頁一樣漂亮3. 《CSS3實戰(zhàn)》筆記--漸變設(shè)計(一)4. ASP.NET Core自定義中間件的方式詳解5. 移動端HTML5實現(xiàn)拍照功能的兩種方法6. CSS3實現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效7. 教你JS更簡單的獲取表單中數(shù)據(jù)(formdata)8. html5手機(jī)觸屏touch事件介紹9. ASP.NET MVC把數(shù)據(jù)庫中枚舉項的數(shù)字轉(zhuǎn)換成文字10. 測試模式 - XSL教程 - 5
