getSession()方法简介
`getSession()`是`HttpServletRequest`接口中定义一个方法
用于获取当前请求所关联`HttpSession`对象
它是实现 Web 应用中用户会话管理(如登录、购物车)核心方法之一
getSession()方法功能简介
功能 | 描述 |
获取当前用户的会话对象 | 用于在多个请求之间共享数据 |
自动创建新会话(可选) | 如果当前没有会话,可以自动创建一个 |
支持会话跟踪 | 实现用户身份识别、状态保持等功能 |
getSession()方法定义
HttpSession getSession(boolean create)
- 参数说明:
- `create = true`:
如果没有会话则创建一个新的
- `create = false`:
如果没有会话则返回`null`
还有一个无参版本
HttpSession getSession()
其方法等价于
`getSession(true)`:即如果没有会话就创建一个新的
例1:获取或创建Session
HttpSession session = request.getSession(); // 如果没有则创建
session.setAttribute("user", user); // 存储用户信息
例2:仅获取已有Session(不创建)
HttpSession session = request.getSession(false); // 如果没有返回 null
if (session != null && session.getAttribute("user") != null) {
// 用户已登录
} else {
// 用户未登录
}
例1:用户登录后保存用户信息
@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)); // 保存用户信息到会话中
response.sendRedirect("home");
} else {
response.sendRedirect("login?error=1");
}
}
}
例2:在其他页面读取会话中的用户信息
@WebServlet("/home")
public class HomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
HttpSession session = request.getSession(false); // 不创建新会话
if (session != null && session.getAttribute("user") != null) {
User user = (User) session.getAttribute("user");
response.setContentType("text/html");
response.getWriter().println("<h1>欢迎回来," + user.getUsername() + "!</h1>");
} else {
response.sendRedirect("login");
}
}
}
例3:手动销毁会话(退出登录))
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate(); // 销毁会话
}
response.sendRedirect("login");
}
}
HttpSession相关说明
建议 | 说明 |
推荐用于存储用户身份信息 | 如用户名、角色、权限等 |
不要存放大量数据 | 否则会影响性能 |
不要依赖会话永久存在 | 服务器重启或会话超时会导致数据丢失 |
可结合监听器使用 | 如 `HttpSessionlistener` 监听在线人数 |
适合用于MVC架构 | Controller 设置 session,View 使用 session 数据 |
`getSession()`应用场景
场景 | 使用方式 |
用户登录状态管理 | 将用户信息存入 session |
购物车实现 | 存储用户选中的商品 |
防止重复提交 | 记录表单提交状态 |
权限控制 | 判断用户是否有权限访问某资源 |
在线人数统计 | 使用 `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;
}
}
常见方法名说明
方法名 | 行为描述 |
`request.getSession()` | 获取当前会话,若不存在则创建 |
`request.getSession(true)` | 等同于上面 |
`request.getSession(false)` | 仅获取已有会话,不会新建 |
返回值 | 说明 |
`HttpSession` 对象 | 成功获取会话 |
`null` | 当`create=false`且没有现有会话时返回null |