如何从 ApplicationListener 方法中获取会话对象 [英] How I can get session object from ApplicationListener method
问题描述
我想在用户身份验证成功后将对象添加到 HttpSession
. 请不要建议使用 SavedRequestAwareAuthenticationSuccessHandler
的解决方案,因为在这个应用程序中有些原因应用程序忽略原始请求.
I want to add object to HttpSession
after successful user authentication. Please don't suggest solution with SavedRequestAwareAuthenticationSuccessHandler
because in this app for some reason application are ingnoring original request.
public class AuthenticationSuccessListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
@Override
public void onApplicationEvent(InteractiveAuthenticationSuccessEvent e) {
//adding object to HttpSession
}
}
推荐答案
据我所知,ApplicationListener
实例只是您的 ApplicationContext
中的 bean.因此,您应该能够将其他 bean 或资源注入其中.
As far as I am aware, ApplicationListener
instances are just beans within your ApplicationContext
. Therefore you should be able to inject other beans or resources into them.
所以要获取对当前 HttpSession
实例的引用:
So to get a reference to the current HttpSession
instance:
public class AuthenticationSuccessListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
@Autowired
private HttpSession httpSession;
@Override
public void onApplicationEvent(InteractiveAuthenticationSuccessEvent e) {
//adding object to HttpSession
}
}
Spring 将使用其 作用域代理机制确保您获得与当前执行线程相关的 HTTPSession
.
Spring will inject the HttpSession
using its scoped proxy mechanism ensuring that you get the HTTPSession
relevant to the current thread of execution.
您还需要确保在 web.xml 中注册了 RequestContextListener
,以便 Spring 可以注入当前的 HTTPSession
.
You'll also need to ensure that you register a RequestContextListener
in your web.xml so that Spring can inject the current HTTPSession
.
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
这篇关于如何从 ApplicationListener 方法中获取会话对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!