java 如何使用session
创建和获取Session
在Java Web应用中,HttpSession对象用于在多个请求之间存储用户数据。通过HttpServletRequest的getSession()方法可以获取或创建Session。调用getSession(true)或直接getSession()会在Session不存在时自动创建。
HttpSession session = request.getSession();
设置Session属性
使用setAttribute方法存储数据到Session中,需要指定属性名和属性值。属性名是字符串,属性值可以是任意对象。
session.setAttribute("username", "JohnDoe");
session.setAttribute("cartItems", cartItemsList);
获取Session属性
通过getAttribute方法并传入属性名来获取存储在Session中的数据。如果属性不存在则返回null。
String username = (String) session.getAttribute("username");
List<String> cartItems = (List<String>) session.getAttribute("cartItems");
移除Session属性
使用removeAttribute方法可以删除Session中的特定属性。需要传入要删除的属性名。
session.removeAttribute("cartItems");
使Session失效
调用invalidate方法会使当前Session失效,清除所有存储的数据。常用于用户注销时。
session.invalidate();
设置Session超时时间
通过setMaxInactiveInterval方法设置Session的最大非活动时间间隔,单位为秒。也可以在web.xml中配置全局超时时间。
session.setMaxInactiveInterval(30 * 60); // 30分钟
监听Session事件
实现HttpSessionListener接口可以监听Session的创建和销毁事件。需要在web.xml中配置监听器或使用注解。

public class MySessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Session created: " + se.getSession().getId());
}
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Session destroyed: " + se.getSession().getId());
}
}
注意事项
Session数据存储在服务器内存中,大量使用会影响性能。敏感数据不应仅依赖Session进行安全验证。在分布式环境中需要考虑Session共享问题,可通过Spring Session等解决方案实现。






