使用监听器Listener实现在线人数统计功能
目录树及使用的文件
1.首先创建一个CountListener类实现HttpSessionListener接口,实现接口的两个方法:sessionCreated和sessionDestroyed。
package listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class CountListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {//当服务器会话创建时的方法
HttpSession session = httpSessionEvent.getSession();
ServletContext ctx = session.getServletContext();//通过httpSessionEvent来获取servletContext对象
Integer onlineCount = (Integer) ctx.getAttribute("onlineCount");//获取servletContext中的onlineCount的值,首先是不存在的
if (onlineCount == null) {
onlineCount = new Integer(1);//当不存在时,往onlineCount里面存值1
} else {
int count = onlineCount.intValue();
onlineCount = new Integer(count + 1);//否则当存在时,onlineCount的值就+1
}
ctx.setAttribute("onlineCount", onlineCount);//将改变的onlineCount值存入session中
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {//当服务器会话关闭时的方法
HttpSession session = httpSessionEvent.getSession();
ServletContext ctx = session.getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("onlineCount");
if (onlineCount == null) {
onlineCount = new Integer(0);
} else {
int count = onlineCount.intValue();
onlineCount = new Integer(count - 1);//当会话关闭时,onlineCount的值就-1
}
ctx.setAttribute("onlineCount", onlineCount);
}
}
2.web.xml配置监听器
<listener>
<listener-class>listener.CountListener</listener-class>
</listener>
3.index.jsp页面取值
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<h1>当前人数:<%=application.getAttribute("onlineCount")%></h1>//上下两种方法都能取值
<%=this.getServletConfig().getServletContext().getAttribute("onlineCount")%>
</body>
</html>
4.展示页面
这里一共开了4个网页,分别是:普通Chrome,隐私Chrome,普通Firefox,隐私Firefox。所以当前人数显示为4.(之前的网页需要刷新)。
这里还有个小bug,在创建会话时,会有以前的session没销毁,导致在线人数不正确。解决方法:redeploy Tomcat服务器