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);}
}