Servlet API 無直接獲取所有 Session 的方法。需自行維護一個全域集合(存放於 ServletContext),在 Session 創建/銷毀時更新。
實現該接口的物件被放入/移出 Session 時,容器自動回調:
valueBound(HttpSessionBindingEvent):屬性添加到 Session 時觸發。valueUnbound(HttpSessionBindingEvent):屬性從 Session 移除/Session 逾時銷毀時觸發。public class SessionBindingNotifier implements HttpSessionBindingListener {
private ServletContext application;
public SessionBindingNotifier(ServletContext application) {
this.application = application;
}
public void valueBound(HttpSessionBindingEvent event) {
HttpSession session = event.getSession();
// 僅當用戶已登錄(Session 中有 user 屬性)才計入在線列表
if (session.getAttribute("user") != null) {
Vector<HttpSession> active = (Vector<HttpSession>) application.getAttribute("activeSessions");
if (active == null) {
active = new Vector<>();
application.setAttribute("activeSessions", active);
}
active.add(session);
}
}
public void valueUnbound(HttpSessionBindingEvent event) {
HttpSession session = event.getSession();
Vector<HttpSession> active = (Vector<HttpSession>) application.getAttribute("activeSessions");
if (active != null) {
active.remove(session);
}
}
}
// 登錄成功時
session.setAttribute("user", user); // 業務用戶對象
session.setAttribute("bindingNotifier", new SessionBindingNotifier(application)); // 觸發 valueBound
// 登出時
Vector<HttpSession> active = (Vector<HttpSession>) application.getAttribute("activeSessions");
if (active != null) active.remove(session);
session.invalidate(); // 銷毀 Session,同時觸發 valueUnbound(雙重保險)
<table>
<tr><th>SessionID</th><th>用戶名</th><th>登錄時間</th><th>最後活動</th></tr>
<%
Vector<HttpSession> active = (Vector<HttpSession>) application.getAttribute("activeSessions");
if (active != null) {
for (HttpSession s : active) {
User u = (User) s.getAttribute("user");
%>
<tr>
<td><%= s.getId() %></td>
<td><%= u != null ? u.getName() : "匿名" %></td>
<td><%= new Date(s.getCreationTime()) %></td>
<td><%= new Date(s.getLastAccessedTime()) %></td>
</tr>
<% } } %>
</table>
activeSessions 亦需分佈式集合。valueUnbound 的僵屍 Session。ConcurrentHashMap<String, HttpSession> (Key=SessionID)。