Spring boot通過HttpSessionListener監(jiān)聽器統(tǒng)計在線人數(shù)的實現(xiàn)代碼
首先說下,這個統(tǒng)計在線人數(shù)有個缺陷,一個人在線可以同時擁有多個session,導(dǎo)致統(tǒng)計有一定的不準(zhǔn)確行。
接下來,開始代碼的編寫,
第一步:實現(xiàn)HttpSessionListener中的方法,加上注解@WebListener
@WebListener
public class SessionListener implements HttpSessionListener{
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
ServletContext context = arg0.getSession().getServletContext();
if (context.getAttribute("count")==null) {
context.setAttribute("count", 0);
}else {
int count = (Integer) context.getAttribute("count");
context.setAttribute("count", count+1);
}
}
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
ServletContext context = arg0.getSession().getServletContext();
if (context.getAttribute("count")==null) {
context.setAttribute("count", 0);
}else {
int count = (Integer) context.getAttribute("count");
if (count<1) {
count = 1;
}
context.setAttribute("count", count-1);
}
HttpSession session = arg0.getSession();
String name = (String) session.getAttribute("name");
HashSet<String> nameSet = (HashSet<String>) context.getAttribute("nameSet");
nameSet.remove(name);
}
}
第二步:控制創(chuàng)建session放入對象
HttpSession session = request.getSession();
session.setAttribute("name", name);
Object count = context.getAttribute("count");
if (count==null) {
count = 0;
}
第三步:啟動類加上注解@ServletComponentScan,這樣才能掃描到監(jiān)聽器
說明,此代碼適用于spring-boot開發(fā)
簡單說下,javaWeb中配置監(jiān)聽器在web.xml中加上
<listener> <listener-class>zjq.listener.SessionListener</listener-class> </listener>
總結(jié)
以上所述是小編給大家介紹的Spring boot通過HttpSessionListener監(jiān)聽器統(tǒng)計在線人數(shù)的實現(xiàn)代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
SpringMVC框架post提交數(shù)據(jù)庫出現(xiàn)亂碼解決方案
這篇文章主要介紹了SpringMVC框架post提交數(shù)據(jù)庫出現(xiàn)亂碼解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
NetBeans安裝提示neatbeans cannot find java 1.8 or higher
今天小編就為大家分享一篇關(guān)于NetBeans安裝提示neatbeans cannot find java 1.8 or higher,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-04-04
靜態(tài)方法中調(diào)用Spring注入過程解析
這篇文章主要介紹了靜態(tài)方法中調(diào)用Spring注入過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11
SpringBoot整合resilience4j實現(xiàn)接口限流
最近在開發(fā)項目的時候,需要用到限流的功能,本文主要介紹了SpringBoot整合resilience4j實現(xiàn)接口限流,具有一定的參考價值,感興趣的可以了解一下2024-01-01

