Session 逾時指使用者在指定時間內無任何請求,伺服器銷毀 Session 釋放記憶體。預設值通常為 30 分鐘 (Tomcat)。設定單位:web.xml 以分鐘為單位,程式碼以秒為單位。
| 方式 | 範圍 | 單位 | 優先序 | 備註 |
|---|---|---|---|---|
| web.xml <session-config> | 全域 (整個 Web App) | 分鐘 | 最低 | 部署描述檔,無需重新編譯 |
| @WebServlet/@WebListener 註解 | 單一 Servlet/Listener | 秒 | 中 | Servlet 3.0+,編譯期決定 |
| HttpSession.setMaxInactiveInterval() | 單一 Session 實例 | 秒 | 最高 | 執行期動態調整,-1 代表永不過期 |
原則:程式碼 > 註解 > web.xml,局部 > 全域
<web-app xmlns="https://xmlns.jcp.org/xml/ns/javaee"
version="4.0">
<session-config>
<session-timeout>30</session-timeout> <!-- 30 分鐘 -->
</session-config>
</web-app>
0 或負數:Session 永不過期 (不建議生產環境)。@WebServlet(urlPatterns = "/login",
initParams = @WebInitParam(name = "sessionTimeout", value = "1800")) // 1800 秒 = 30 分鐘
public class LoginServlet extends HttpServlet {
// 實際仍需在程式碼中讀取 initParam 並呼叫 setMaxInactiveInterval
}
註解本身不直接生效,需搭配程式碼:
@Override
public void init(ServletConfig config) {
String timeoutStr = config.getInitParameter("sessionTimeout");
if (timeoutStr != null) {
try {
this.defaultTimeout = Integer.parseInt(timeoutStr);
} catch (NumberFormatException ignored) {}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session = req.getSession(true);
session.setMaxInactiveInterval(this.defaultTimeout); // 套用
}
// 登入成功後,依使用者角色給予不同逾時
HttpSession session = request.getSession(true);
if ("admin".equals(user.getRole())) {
session.setMaxInactiveInterval(60 * 60); // 管理員 1 小時
} else if ("vip".equals(user.getRole())) {
session.setMaxInactiveInterval(45 * 60); // VIP 45 分鐘
} else {
session.setMaxInactiveInterval(30 * 60); // 一般 30 分鐘
}
// 永不過期 (慎用):session.setMaxInactiveInterval(-1);
# application.yml
server:
servlet:
session:
timeout: 30m # 支援單位:s, m, h, d
# tracking-modes: cookie # 僅用 Cookie 追蹤 Session
或程式化配置:
@Configuration
public class SessionConfig {
@Bean
public TomcatServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addContextCustomizers(context -> context.setSessionTimeout(30)); // 分鐘
return factory;
}
}
HttpSession session = request.getSession(false); // 不建立新 Session
if (session != null) {
int maxInactive = session.getMaxInactiveInterval(); // 取得秒數
long lastAccessed = session.getLastAccessedTime(); // 最後存取毫秒時間戳
long creationTime = session.getCreationTime();
// 手動登出/銷毀
session.invalidate();
}