HttpSessionListener用于监听用户session的创建和销毁,实现该接口的监听器需要实现sessionCreated和sessionDestroyed方法
HttpSessionAttributeListener用于监听HttpSession范围内属性的变化,需实现attributeAdded、attributeRemoved、attributeReplaced三个方法,同ServletRequestAttributeListener、ServletContextAttributeListener的使用方法相似,具体参考前两篇博客
1. 实现Listener接口OnlineListener.java,统计在线用户的信息
package test;
import javax.servlet.*;
import javax.servlet.http.*;import java.util.*;
public class OnlineListener implements HttpSessionListener{
//当用户与服务器之间开始session时触发该方法
public void sessionCreated(HttpSessionEvent se){
HttpSession session = se.getSession();
ServletContext application = session.getServletContext();
//获取session ID
String sessionId = session.getId();
//如果是一次新的会话
if (session.isNew()){
String user = (String)session.getAttribute("user");
//未登录用户当游客处理
user = (user == null) ? "游客" : user;
Map<String , String> online = (Map<String , String>)application.getAttribute("online");
if (online == null){
online = new Hashtable<String , String>();
}
//将用户在线信息放入Map中
online.put(sessionId , user);
application.setAttribute("online" , online);
}
}
//当用户与服务器之间session断开时触发该方法
public void sessionDestroyed(HttpSessionEvent se){
HttpSession session = se.getSession();
ServletContext application = session.getServletContext();
String sessionId = session.getId();
Map<String , String> online = (Map<String , String>)application.getAttribute("online");
if (online != null){
//删除该用户的在线信息
online.remove(sessionId);
}
application.setAttribute("online" , online);
}
}
2. 显示在线用户的信息online.jsp
<%@ page contentType="text/html; charset=GBK" language="java"
errorPage=""%>
<%@ page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>用户在线信息</title>
<meta name="website" content="http://www.crazyit.org" />
</head>
<body>
在线用户:
<table width="400" border="1">
<%
Map<String, String> online = (Map<String, String>) application.getAttribute("online");
for (String sessionId : online.keySet()) {
%>
<tr>
<td><%=sessionId%>
<td><%=online.get(sessionId)%>
</tr>
<%}%>
</body>
</html>