Springboot 项目一启动就获取HttpSession的两种方法
更新时间:2025年10月21日 09:43:58 作者:梁云亮
在SpringBoot项目中,HttpSession是有状态的,通常只有在用户发起 HTTP请求并建立会话后才会创建,因此,在项目启动时是无法获取到 HttpSession,下面就来介绍一下Springboot启动就获取HttpSession,感兴趣的可以了解一下
在 Spring Boot 项目中,HttpSession 是有状态的,通常只有在用户发起 HTTP 请求并建立会话后才会创建。因此,在项目启动时(即应用刚启动还未处理任何请求)是无法获取到 HttpSession 的。
方法一:使用 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 WebConfig implements WebMvcConfigurer {
@Autowired
private SessionInitInterceptor sessionInitInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(sessionInitInterceptor);
}
}
到此这篇关于Springboot 项目一启动就获取HttpSession的两种方法的文章就介绍到这了,更多相关Springboot启动就获取HttpSession内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
maven中no main manifest attribute的问题解决
本文主要介绍了maven中no main manifest attribute的问题解决,这个错误通常意味着Spring Boot应用在启动时遇到了问题,下面就来具体介绍一下,感兴趣的可以了解一下2024-08-08
SpringBoot中@Autowired与@Resource的区别小结
本文主要介绍了SpringBoot中@Autowired与@Resource的区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2025-01-01
springboot jdbcTemplate 多源配置及特殊场景使用说明
文章讲解Spring Boot中JdbcTemplate多数据源配置,涵盖单服务器多库与多服务器多库两种模式,本文结合特殊场景使用分析给大家介绍的非常详细,感兴趣的朋友一起看看吧2025-07-07


最新评论