自定义MySessionListener实现HttpSessionListener接口
package com.sessionListener.listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
private long onlineCount;
public void sessionCreated(HttpSessionEvent event) {
// TODO Auto-generated method stub
this.onlineCount=this.onlineCount+1;
//保存在application作用域
event.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
}
public void sessionDestroyed(HttpSessionEvent event) {
// TODO Auto-generated method stub
this.onlineCount=this.onlineCount-1;
event.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
}
}
在web.xml中配置该监听器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<!-- 配置自定义监听器 -->
<listener>
<listener-class>com.sessionListener.listener.MySessionListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping></web-app>
jsp页面
当前在线人数:${application.onlineCount }
对每一个正在访问的用户,J2EE应用服务器会为其建立一个对应的HttpSession对象。当一个浏览器第一次访问网站的时候,J2EE应用服务器会新建一个HttpSession对象,并触发HttpSession创建事件,如果注册了HttpSessionListener事件监听器,则会调用HttpSessionListener事件监听器的sessionCreated方法。相反,当这个浏览器访问结束超时的时候,J2EE应用服务器会销毁相应的HttpSession对象,触发HttpSession销毁事件,同时调用所注册HttpSessionListener事件监听器的sessionDestroyed方法。
可见,对应于一个用户访问的开始和结束,相应的有sessionCreated方法和sessionDestroyed方法执行。这样,我们只需要在HttpSessionListener实现类的sessionCreated方法中让计数器加1,在sessionDestroyed方法中让计数器减1,就轻松实现了网站在线人数的统计功能。