Springboot 項目一啟動就獲取HttpSession的兩種方法
在 Spring Boot 項目中,HttpSession 是有狀態(tài)的,通常只有在用戶發(fā)起 HTTP 請求并建立會話后才會創(chuàng)建。因此,在項目啟動時(即應(yīng)用剛啟動還未處理任何請求)是無法獲取到 HttpSession 的。
方法一:使用 HttpSessionListener(監(jiān)聽 session 創(chuàng)建)
@Component
public class MySessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
// 當 session 被創(chuàng)建時執(zhí)行
System.out.println("Session created: " + se.getSession().getId());
se.getSession().setAttribute("initData", "some value");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
// 當 session 銷毀時執(zhí)行
}
}
方法二:使用攔截器或過濾器設(shè)置 Session 數(shù)據(jù)
@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);
}
}
到此這篇關(guān)于Springboot 項目一啟動就獲取HttpSession的兩種方法的文章就介紹到這了,更多相關(guān)Springboot啟動就獲取HttpSession內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
maven中no main manifest attribute的問題解決
本文主要介紹了maven中no main manifest attribute的問題解決,這個錯誤通常意味著Spring Boot應(yīng)用在啟動時遇到了問題,下面就來具體介紹一下,感興趣的可以了解一下2024-08-08
SpringBoot中@Autowired與@Resource的區(qū)別小結(jié)
本文主要介紹了SpringBoot中@Autowired與@Resource的區(qū)別小結(jié),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2025-01-01
SpringBoot集成quartz實現(xiàn)定時任務(wù)詳解
最為常用定時任務(wù)框架是Quartz,并且Spring也集成了Quartz的框架,Quartz不僅支持單實例方式還支持分布式方式。本文主要介紹Quartz,基礎(chǔ)的Quartz的集成案例本,以及實現(xiàn)基于數(shù)據(jù)庫的分布式任務(wù)管理和控制job生命周期2022-08-08
MyBatis-Flex實現(xiàn)多表聯(lián)查(自動映射)
我們可以輕松的使用 Mybaits-Flex 鏈接任何數(shù)據(jù)庫,本文主要介紹了MyBatis-Flex實現(xiàn)多表聯(lián)查(自動映射),具有一定的參考價值,感興趣的可以了解一下2024-06-06
關(guān)于Spring?Cloud實現(xiàn)日志管理模塊
這篇文章主要介紹了關(guān)于Spring?Cloud實現(xiàn)日志管理模塊問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
springboot?jdbcTemplate?多源配置及特殊場景使用說明
文章講解Spring?Boot中JdbcTemplate多數(shù)據(jù)源配置,涵蓋單服務(wù)器多庫與多服務(wù)器多庫兩種模式,本文結(jié)合特殊場景使用分析給大家介紹的非常詳細,感興趣的朋友一起看看吧2025-07-07

