HttpSession简介说明

欢喜 Servlet 发布时间:2025-05-28 09:34:29 阅读数:12088 1
这是一篇HttpSession的大白话文章,通过这一篇文章的学习,我们可以彻底的掌握HttpSession的相关知识,如下所示

HttpSession简介

`HttpSession`是Java Servlet API中一个接口
   用于在多个HTTP请求之间保持用户状态(即会话)
    它是实现Web应用中“用户登录”、“购物车”等功能核心机制 

HttpSession功能

功能描述
会话管理在用户访问网站的整个过程中保存用户信息
跨请求共享数据如用户身份、购物车内容等
支持会话超时机制可设置会话过期时间,防止资源浪费
支持会话监听可监听会话创建和销毁事件
支持分布式部署(如集群)结合 Session Replication或 Redis 等实现会话共享

HttpSession会话生命周期

阶段描述
创建会话第一次调用`request.getSession()`时自动创建(或 `getSession(true)`)
使用会话通过`setAttribute()`/`getAttribute()` 存取数据
销毁会话调用`session.invalidate()`或超时后自动销毁

HttpSession常用方法

方法名 描述
`setAttribute(String name, Object value)`将对象绑定到会话中
`getAttribute(String name)`获取会话中绑定的对象
`removeAttribute(String name)` 移除指定名称的属性
`getId()` 获取会话 ID(JSESSIONID)
`setMaxInactiveInterval(int interval)` 设置会话最大不活动时间(单位:秒)
`invalidate()`销毁当前会话
`isNew()`判断该会话是否是新创建

HttpSession例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:设置会话超时时间

可在`web.xml`中全局设置会话超时时间(单位:分钟)
 
<session-config>
    <session-timeout>30</session-timeout> <!-- 30 分钟无操作后失效 -->
</session-config>

 或
   在代码中为某个会话单独设置:
      session.setMaxInactiveInterval(60 * 30); // 30 分钟

例4:
手动销毁会话(退出登录)

@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 数据

HttpSession使用场景

场景使用方式
用户登录状态管理将用户信息存入 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;
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/Servlet/202505/322.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者