Java Web監(jiān)聽器Listener接口原理及用法實例
更新時間:2020年06月23日 15:54:25 作者:Esrevinud的筆記
這篇文章主要介紹了Java Web監(jiān)聽器Listener接口原理及用法實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
監(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" id="WebApp_ID" 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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java打印從1到100的值(break,return斷句)
java 先寫一個程序,打印從1到100的值。之后修改程序,通過使用break關(guān)鍵詞,使得程序在打印到98時退出。然后嘗試使用return來達到相同的目的2017-02-02SpringBoot異步調(diào)用方法實現(xiàn)場景代碼實例
這篇文章主要介紹了SpringBoot異步調(diào)用方法實現(xiàn)場景代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04Spring注解@Qualifier的使用&&與@Primary注解的不同
今天帶你了解一下Spring框架中的@Qualifier?注解,它解決了哪些問題,以及如何使用它,我們還將了解它與?@Primary?注解的不同之處,感興趣的朋友跟隨小編一起看看吧2023-10-10