[英]Populate user session after login
成功登錄后,我需要在用戶會話中放置一些值(String和Integer值)。
我在我的網絡應用程序中使用Spring MVC + Spring Security(均為v3.2.x)。
Spring是否有一些常見的方法來攔截會話啟動? 實現HttpSessionListener
並在我的應用程序中注冊它是否正確?
我最終決定實現一個自定義的ApplicationListener
來處理用戶登錄:
public class LoggedUserListener implements
ApplicationListener<AuthenticationSuccessEvent> {
@Autowired
private HttpSession session;
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
session.setAttribute("key", "value");
}
}
並在我的Spring配置中聲明了一個bean:
<bean class="it.webapp.LoggedUserListener" />
它完美地運作。
如果您使用的是Spring MVC + Spring Security,那么可能需要查看org.springframework.security.web.session.HttpSessionEventPublisher
該類的javadoc說:
將HttpSessionApplicationEvents發布到Spring Root WebApplicationContext。
將javax.servlet.http.HttpSessionListener.sessionCreated()映射到HttpSessionCreatedEvent。
我的理解是你需要添加:
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
並且您的類需要擴展ApplicationListener
才能接收這些事件
public class SessionPopulatorThing implements ApplicationListener<HttpSessionCreatedEvent>{
//repository, service attributes go here
public void onApplicationEvent(HttpSessionCreatedEvent httpSessionCreatedEvent){
//populate with defaults
}
}
主要的好處是它與Spring Core + Spring Security兼容,並且通過一些額外的配置,你可以在Spring Security的會話管理中獲得並發管理功能。 Spring安全參考文檔中有更多相關內容:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.