HttpSessionListener用于实现session的创建和销毁。
统计在线人数
package com.xxx.listener;
import java.util.Hashtable;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class OnlineListener implements HttpSessionListener {
//当与服务器之间开始session时触发该方法
@Override
public void sessionCreated(HttpSessionEvent arg0) {
HttpSession session=arg0.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>();
}
online.put(sessionId, user);
application.setAttribute("online", online);
}
}
//当用户与服务器之间session断开时触发该方法
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
HttpSession session=arg0.getSession();
ServletContext application=session.getServletContext();
//获取session id
String sessionId=session.getId();
Map<String,String> online=(Map<String, String>) application.getAttribute("online");
if(online!=null){
//删除该用户在线信息
online.remove(sessionId);
}
application.setAttribute("online", online);
}
}
online.jsp
<body>
<%
Map<String,String> online=(Map<String,String>)application.getAttribute("online");
for(String sessionId:online.keySet()){
%>
<tr>
<td><%=sessionId %></td>
<td><%online.get(sessionId) %></td>
</tr>
<%} %>
</body>