1. 程式人生 > >Listener的使用(監聽使用者session的開始和結束,HttpSession範圍內屬性的改變)

Listener的使用(監聽使用者session的開始和結束,HttpSession範圍內屬性的改變)

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>