首先說下,這個統計在線人數有個缺陷,一個人在線可以同時擁有多個session,導致統計有一定的不准確行。
接下來,開始代碼的編寫,
第一步:實現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); } }第二步:控制創建session放入對象
HttpSession session = request.getSession(); session.setAttribute("name", name); Object count = context.getAttribute("count"); if (count==null) { count = 0; }第三步:啟動類加上註解@ServletComponentScan,這樣才能掃描到監聽器
說明,此代碼適用於spring-boot開發
簡單說下,javaWeb中配置監聽器在web.xml中加上
<listener> <listener-class>zjq.listener.SessionListener</listener-class> </listener>
總結
以上所述是小編給大家介紹的Spring boot通過HttpSessionListener監聽器統計在線人數的實現代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!