下文笔者讲述setMaxInactiveInterval()方法的功能简介说明,如下所示
setMaxInactiveInterval()方法简介
`setMaxInactiveInterval(int interval)`
是`HttpSession`接口中定义一个方法
用于设置当前会话的最大不活动时间(即超时时间)
是实现Web应用中
自动销毁用户会话机制
常用于控制用户的登录状态在一定时间内无操作后自动失效(如“15分钟未操作自动登出”)
setMaxInactiveInterval()方法功能
功能 | 描述 |
设置会话的不活动超时时间 | 单位为秒,从最后一次请求开始计算 |
会话超时后自动销毁 | 如果用户在设定时间内没有再次访问,服务器将自动销毁该 Session |
控制用户登录有效期 | 常用于安全场景,防止长时间保持登录状态 |
setMaxInactiveInterval()方法定义
void setMaxInactiveInterval(int interval)
- 参数说明:
- `interval`:以秒为单位的超时时间
- `0` 或负值:通常表示永不过期(但不同容器行为可能不同)
- `60 * 30`:表示 30 分钟无操作后过期
- 例:
session.setMaxInactiveInterval(60 * 30); // 30 分钟无操作后销毁
例1:设置会话超时时间为10分钟
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("admin".equals(username) && "123456".equals(password)) {
HttpSession session = request.getSession();
session.setAttribute("user", new User(username));
// 设置会话最大不活动时间为 10 分钟
session.setMaxInactiveInterval(60 * 10);
response.sendRedirect("home");
} else {
response.sendRedirect("login?error=1");
}
}
}
例2:全局配置(web.xml)
<session-config>
<session-timeout>30</session-timeout> <!-- 单位:分钟 -->
</session-config>
注意事项:
此设置是 【分钟级】
而`setMaxInactiveInterval()`是【秒级】
setMaxInactiveInterval()方法使用场景
场景 | 使用方式 |
后台管理系统 | 设置15~30分钟超时,防止忘记登出 |
银行/金融类系统 | 设置较短超时时间(如 5 分钟) |
多租户系统 | 不同租户可设置不同的超时策略 |
安全审计要求高的系统 | 自动清理长时间空闲的会话 |
移动端API会话管理 | 结合 Token 实现更细粒度的控制 |
`setMaxInactiveInterval()` 同 `invalidate()`对比
方法名 | 行为 | 是否立即销毁 |
`setMaxInactiveInterval(int seconds)` | 设置会话最大不活动时间 | 不立即销毁 |
`invalidate()` | 显式销毁会话 | 立即销毁 |
会话超时后的常见的现象
行为 | 描述 |
用户再次访问 | 服务器检测到 Session 已过期,创建新的 Session |
获取属性失败 | `getAttribute()` 返回 `null` |
触发监听器 | 如 `HttpSessionlistener.sessionDestroyed()` |
Cookie 仍然存在 | 浏览器仍携带旧的`JSESSIONID`,但服务器已丢失对应数据 |
HttpSessionListener示例:监听会话销毁事件
@WebListener
public class SessionCounterListener implements HttpSessionListener {
private static int activeSessions = 0;
@Override
public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
System.out.println("新用户上线,当前在线人数:" + activeSessions);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
activeSessions--;
System.out.println("会话超时或被销毁,当前在线人数:" + activeSessions);
}
public static int getActiveSessions() {
return activeSessions;
}
}
当会话因超时被销毁时,会触发 `sessionDestroyed()` 方法。