Springboot 项目一启动就获取HttpSession的两种方法
作者:梁云亮
在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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
