当前位置: 首页 > article >正文

Springboot 项目一启动就获取HttpSession

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

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

@Component
public class MySessionListener implements HttpSessionListener {@Overridepublic void sessionCreated(HttpSessionEvent se) {// 当 session 被创建时执行System.out.println("Session created: " + se.getSession().getId());se.getSession().setAttribute("initData", "some value");}@Overridepublic void sessionDestroyed(HttpSessionEvent se) {// 当 session 销毁时执行}
}

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

@Component
public class SessionInitInterceptor implements HandlerInterceptor {@Overridepublic 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 WebConfig implements WebMvcConfigurer {@Autowiredprivate SessionInitInterceptor sessionInitInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(sessionInitInterceptor);}
}
http://www.lryc.cn/news/2397475.html

相关文章:

  • PostgreSQL的扩展 insert_username
  • 【机器学习基础】机器学习入门核心算法:层次聚类算法(AGNES算法和 DIANA算法)
  • Google Play的最新安全变更可能会让一些高级用户无法使用App
  • 深度学习篇---人脸识别中的face-recognition库和深度学习
  • (11)java+ selenium->元素定位之By_tag_name
  • React---day5
  • Java开发之定时器学习
  • HealthBench医疗AI评估基准:技术路径与核心价值深度分析(上)
  • Windows+VSCode搭建小智(xiaozhi)开发环境
  • VueScan Pro v9.8.45.08 一款图像扫描软件,中文绿色便携版
  • FreeRTOS通俗理解指南:基础概念 + 架构+ 内核组件+练手实验
  • Python后端开发实战:从0到1搭建高可用API服务
  • 房屋租赁系统 Java+Vue.js+SpringBoot,包括房屋信息、看房申请、租赁合同、房屋报修、收租信息、维修数据、租客管理、公告管理模块
  • 4、ubuntu系统 | 文本和目录操作函数
  • docker部署ELK,ES开启安全认证
  • ASP.NET MVC添加视图示例
  • 自动驾驶中的路径跟踪:Python实现与技术解析
  • 前端面试题目-高频问题集合
  • MyBatis源码解析:从 Mapper 接口到 SQL 执行的完整链路
  • 50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | Form Wave(表单label波动效果)
  • 双目相机深度的误差分析(基线长度和相机焦距的选择)
  • Pytorch Geometric官方例程pytorch_geometric/examples/link_pred.py环境安装教程及图数据集制作
  • React---day6、7
  • hook组件-useEffect、useRef
  • 功能结构整理
  • 企业级开发中的 maven-mvnd 应用实践
  • yolov12毕设前置知识准备 1
  • 随机游动算法解决kSAT问题
  • 《Discuz! X3.5开发从入门到生态共建》第1章 Discuz! 的前世今生-优雅草卓伊凡
  • azure web app创建分步指南系列之一