使用Servlet监听器统计在线用户使用Servlet监听器可以统计在线用户,具体实现方法如下:1
通过ServletContext监听初始化一个application对象,保存在线用户列表;2
通过Session监听当用户登录成功设置Session属性时将用户名保存在列表中;3
通过Session监听当用户注销登录时将用户名从列表中删除
实例:OnlineListener
java:packagemgc
listener
test;importjava
*;importjavax
servlet
*;importjavax
servlet
*;publicclassOnlineListenerimplementsServletContextListener,ServletContextAttributeListener,HttpSessionListener,HttpSessionAttributeListener{privateServletContextapplication=null;privateHttpSessionsession=null;publicvoidcontextInitialized(ServletContextEventsce){//初始化一个application对象this
application=sce
getServletContext();//设置一个列表属性,用于保存在线用户名this
application
setAttribute("online",newArrayList());}publicvoidcontextDestroyed(ServletContextEventsce){}publicvoidattributeAdded(ServletContextAttributeEventscab){}publ