JAVA 获取在线用户数的方法
摘要: 在互联网的应用中,通常需要统计当前时间使用系统的人数,用来衡量网络的使用量以及稳定性的数据,如何实现这种功能呢,其实通过 java servlet listener 就可以实现,下面是实现的方法.1. 编写 扩展实现 HttpSessionListener 接口.2. 在web.xml 中配置listener.
在互联网的应用中,通常需要统计当前时间使用系统的人数,用来衡量网络的使用量以及稳定性的数据,如何实现这种功能呢,其实通过 java servlet listener 就可以实现,下面是实现的方法.
1. 编写 扩展实现 HttpSessionListener 接口.
2. 在web.xml 中配置listener.
第一步,编写如下扩展
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class OnlineCounter extends HttpServlet implements HttpSessionListener, HttpSessionAttributeListener,HttpSessionBindingListener { public OnlineCounter(){ System.out.println("OnlineCounter initialized."); } private static final long serialVersionUID = 1L; private static int sessionCounter = 0; private static int attributeCounter = 0; public void sessionCreated(HttpSessionEvent se) { sessionCounter++; System.out.println("session created"); } public void sessionDestroyed(HttpSessionEvent se) { sessionCounter--; System.out.println("session destroied"); } public void attributeAdded(HttpSessionBindingEvent se) { attributeCounter++; System.out.println("attribute added"); } public void attributeRemoved(HttpSessionBindingEvent se) { attributeCounter--; System.out.println("attribute removed"); } public void attributeReplaced(HttpSessionBindingEvent se) { System.out.println(se.getName()+" replaced"); } public void valueBound(HttpSessionBindingEvent event){ System.out.println(event.getName()+"_Bound_"+event.getValue()); } public void valueUnbound(HttpSessionBindingEvent event) { System.out.println(event.getName()+"_Unbound_"+event.getValue()); } public static int getOnlineSession() { return sessionCounter; } public static int getOnlineAttribute() { return attributeCounter; } }
第二步:在web.xml 中配置:
com.yihaomen.OnlineCounter
在需要显示的地方调用方法 OnlineCounter.getOnlineSession(), 就可以得到当前的在线人数。
大飞 评论于: 2015-04-04