开发者

Springboot 项目一启动就获取HttpSession的两种方法

开发者 https://www.devze.com 2025-10-21 10:34 出处:网络 作者: 梁云亮
目录方法一:使用 HttpSessionListener(监听 session 创建)方法二:使用拦截器或过滤器设置 Session 数据在 Spring Boot 项目中,HttpSession 是有状态的,通常www.devze.com只有在用户发起 HTTP 请求并建立会话后
目录
  • 方法一:使用 HttpSessionListener(监听 session 创建)
  • 方法二:使用拦截器或过滤器设置 Session 数据

在 Spring Boot 项目中,HttpSession 是有状态的,通常www.devze.com只有在用户发起 HTTP 请求并建立会话后才会创建。因此,在项目启动时(即应用刚启动还未处理任何请求)是无法获取到 HttpphpSession android的。

方法一:使用 HttpSessionListener(监听 session 创建)

@Component
public class MySessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        // 当 session 被创建时执行
        System.out.println("Session created: " + se.getSession().getId());
        se.getSession().setAttribute("initData", "some value");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // 当 session 销毁时执行
    }
}

方法二:使用拦截器或过滤器设置 Session 数据

@Component
public class SessionInitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        HttpSession session = request.getSession();
        if (session.getAttribute("initData") == null) {
            session.setAttribute("initData", "initialized on first request");
        }
        return true;
    }
}

并在配置中注册:

@Configuration
public class W编程客栈ebConfig implements WebMvcConfigurer {

    @Autowired
    private SessionInitInterceptor sessionInitInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sessionInitInterceptor);
    }
}

到此这篇关于Springboot 项目一启动就获取HttpSession的两种方法的文章就介绍到这了,更多相关Springboot启动就获取HttpSession内容请搜索编程客栈(www.cppcns.javascriptcom)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号