session.setMaxInactiveInterval(900); // 秒為單位,900 秒 = 15 分鐘<session-config>
<session-timeout>1</session-timeout> <!-- 分鐘為單位 -->
</session-config>
$CATALINA_HOME/conf/web.xml 中的 <session-config>,預設 30 分鐘。修改此處影響所有未覆蓋的 Web 應用。當 Session 逾時或手動 invalidate() 時,容器會觸發監聽器事件。實作 HttpSessionListener 可執行清理邏輯:
public class SessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
HttpSession ses = event.getSession();
String id = ses.getId() + ses.getCreationTime();
SummerConstant.UserMap.put(id, Boolean.TRUE); // 記錄在線用戶
}
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession ses = event.getSession();
String id = ses.getId() + ses.getCreationTime();
synchronized (this) {
SummerConstant.USERNUM--; // 在線人數 -1
SummerConstant.UserMap.remove(id); // 移除用戶記錄
}
}
}
<listener>
<listener-class>com.demo.SessionListener</listener-class>
</listener>
sessionDestroyed 執行時 Session 已無效,勿嘗試存取 Session 屬性(會拋出 IllegalStateException)。