java中如何使用session
创建和获取Session
在Java Web应用中,可以通过HttpServletRequest对象获取当前请求的Session。如果Session不存在,可以通过参数控制是否自动创建。
// 获取Session,若不存在则自动创建(默认true)
HttpSession session = request.getSession();
// 获取Session,若不存在则返回null(参数为false)
HttpSession session = request.getSession(false);
存储和读取Session数据
Session通过键值对存储数据,支持任意可序列化的Java对象。

// 存储数据
session.setAttribute("username", "Alice");
// 读取数据
String username = (String) session.getAttribute("username");
// 删除数据
session.removeAttribute("username");
设置Session超时时间
Session默认超时时间由服务器配置(如Tomcat默认为30分钟),可通过代码动态调整。

// 设置超时时间为20分钟(单位:秒)
session.setMaxInactiveInterval(20 * 60);
// 获取当前超时时间
int timeout = session.getMaxInactiveInterval();
销毁Session
主动销毁Session会清除所有存储的数据,通常用于用户登出场景。
session.invalidate();
监听Session生命周期
通过实现HttpSessionListener接口,可以监听Session的创建和销毁事件。
public class CustomSessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Session created: " + se.getSession().getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Session destroyed: " + se.getSession().getId());
}
}
注意事项
- 线程安全:Session对象本身是线程安全的,但存储的数据需自行处理并发问题。
- 分布式环境:在集群部署时,需确保Session共享(如使用Redis或数据库存储)。
- 性能影响:存储大量数据会占用服务器内存,建议仅存储必要信息。






