事件监听之统计当前在线人数案例
Posted gdwkong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了事件监听之统计当前在线人数案例相关的知识,希望对你有一定的参考价值。
1 import javax.servlet.ServletContext; 2 import javax.servlet.ServletContextEvent; 3 import javax.servlet.ServletContextListener; 4 import javax.servlet.annotation.WebListener; 5 import javax.servlet.http.HttpSessionAttributeListener; 6 import javax.servlet.http.HttpSessionEvent; 7 import javax.servlet.http.HttpSessionListener; 8 import javax.servlet.http.HttpSessionBindingEvent; 9 10 @WebListener() 11 public class CountListener implements HttpSessionListener { 12 private int count=0; 13 public void sessionCreated(HttpSessionEvent hse) { 14 count++; 15 ServletContext context = hse.getSession ().getServletContext (); 16 context.setAttribute ("count",new Integer (count)); 17 } 18 19 @Override 20 public void sessionDestroyed(HttpSessionEvent hse) { 21 count--; 22 ServletContext context = hse.getSession ().getServletContext (); 23 context.setAttribute ("count",new Integer (count)); 24 } 25 }
index.jsp
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>$Title$</title> 5 </head> 6 <body> 7 <h3> 8 当前在线人数为:<%=application.getAttribute("count")%> 9 </h3> 10 <a href="<%=response.encodeURL ("logout.jsp")%>">退出系统</a> 11 </body> 12 </html>
logout.jsp
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <%session.invalidate();%> 8 <h3>您已退出系统</h3> 9 </body> 10 </html>
采用不同的浏览器访问,防止公用一个session对象
以上是关于事件监听之统计当前在线人数案例的主要内容,如果未能解决你的问题,请参考以下文章