Servlet 监听 Session 实现用户计数
本文最后更新于:2024年3月18日 凌晨
Servlet 监听 Session 实现用户计数
pom.xml
1 2 3 4 5 6
| <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency>
|
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public class UserCount implements HttpSessionListener { @Override 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 = 1; }else{ int count = onlineCount;
onlineCount = count + 1; } ctx.setAttribute("OnlineCount",onlineCount); }
@Override public void sessionDestroyed(HttpSessionEvent se) { ServletContext ctx = se.getSession().getServletContext(); se.getSession().invalidate(); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount == null) { onlineCount = 0; }else{ int count = onlineCount;
onlineCount = count - 1; } ctx.setAttribute("OnlineCount",onlineCount); }
}
|