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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
mybatis-plus实体类中出现非数据库映射字段解决办法
这篇文章主要介绍了mybatis-plus实体类中出现非数据库映射字段解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-03-03
spring-boot-maven-plugin:打包时排除provided依赖问题
这篇文章主要介绍了spring-boot-maven-plugin:打包时排除provided依赖问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-04-04
mac下idea启动web项目报错java.net.SocketException:socket closed
本文主要介绍了作者在项目启动时遇到的一个问题——无法打开调试端口,经过一系列排查和尝试,最终发现是由于权限问题导致的,作者还分享了如何修改文件权限的方法,并提醒大家不要随意kill掉占用端口的进程2024-12-12


最新评论