JavaWeb之監(jiān)聽器案例講解
1. 監(jiān)聽器
實現(xiàn)一個監(jiān)聽器的接口;(有n種監(jiān)聽器)
1.1 編寫一個監(jiān)聽器(實現(xiàn)監(jiān)聽器接口)
OnlineCountListener .java
package com.tian.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//統(tǒng)計網(wǎng)站在線人數(shù) : 統(tǒng)計session
public class OnlineCountListener implements HttpSessionListener {
//創(chuàng)建session監(jiān)聽: 看你的一舉一動
//一旦創(chuàng)建Session就會觸發(fā)一次這個事件!
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount == null) {
onlineCount = new Integer(1);
} else {
int count = onlineCount.intValue();
onlineCount = new Integer(count + 1);
}
ctx.setAttribute("OnlineCount", onlineCount);
}
//銷毀session監(jiān)聽
//一旦銷毀Session就會觸發(fā)一次這個事件!
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount == null) {
onlineCount = new Integer(0);
} else {
int count = onlineCount.intValue();
onlineCount = new Integer(count - 1);
}
ctx.setAttribute("OnlineCount", onlineCount);
}
/*
Session銷毀:
1. 手動銷毀 getSession().invalidate();
2. 自動銷毀
web.xml
<session-config>
<!--1分鐘后session自動銷毀-->
<session-timeout>1</session-timeout>
</session-config>
*/
}
1.2 配置監(jiān)聽器
web.xml
<!--注冊監(jiān)聽器-->
<listener>
<listener-class>com.tian.listener.OnlineCountListener</listener-class>
</listener>
1.3 啟動服務器


到此這篇關于JavaWeb之監(jiān)聽器案例講解的文章就介紹到這了,更多相關JavaWeb之監(jiān)聽器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot使用定時器@Scheduled不管用的解決
這篇文章主要介紹了springboot使用定時器@Scheduled不管用的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
IDEA2021.2配置docker如何將springboot項目打成鏡像一鍵發(fā)布部署
這篇文章主要介紹了IDEA2021.2配置docker如何將springboot項目打成鏡像一鍵發(fā)布部署,本文圖文實例相結合給大家介紹的非常詳細,需要的朋友可以參考下2021-09-09
Java調(diào)用基于Ollama本地大模型的實現(xiàn)
本文主要介紹了Java調(diào)用基于Ollama本地大模型的實現(xiàn),實現(xiàn)文本生成、問答、文本分類等功能,開發(fā)者可以輕松配置和調(diào)用模型,具有一定的參考價值,感興趣的可以了解一下2025-03-03
使用Spring?Batch實現(xiàn)大數(shù)據(jù)處理的操作方法
通過使用Spring?Batch,我們可以高效地處理大規(guī)模數(shù)據(jù),本文介紹了如何配置和實現(xiàn)一個基本的Spring?Batch作業(yè),包括讀取數(shù)據(jù)、處理數(shù)據(jù)和寫入數(shù)據(jù)的全過程,感興趣的朋友跟隨小編一起看看吧2024-07-07
Springboot多數(shù)據(jù)源配置之整合dynamic-datasource方式
這篇文章主要介紹了Springboot多數(shù)據(jù)源配置之整合dynamic-datasource方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03

