【问题标题】:How I can get session object from ApplicationListener method如何从 ApplicationListener 方法获取会话对象
【发布时间】:2013-11-16 15:06:34
【问题描述】:

我想在成功的用户身份验证后将对象添加到HttpSession请不要建议使用SavedRequestAwareAuthenticationSuccessHandler 的解决方案,因为在这个应用程序中由于某种原因应用程序忽略了原始请求。

public class AuthenticationSuccessListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
    @Override
    public void onApplicationEvent(InteractiveAuthenticationSuccessEvent e) {
        //adding object to HttpSession
    }
} 

【问题讨论】:

    标签: spring spring-mvc spring-security


    【解决方案1】:

    据我所知,ApplicationListener 实例只是您的 ApplicationContext 中的 bean。因此,您应该能够将其他 bean 或资源注入其中。

    所以要获得对当前HttpSession 实例的引用:

    public class AuthenticationSuccessListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
    
    @Autowired
    private HttpSession httpSession;
    
            @Override
            public void onApplicationEvent(InteractiveAuthenticationSuccessEvent e) {
                   //adding object to HttpSession
            }
    }
    

    Spring 将使用其scoped proxy mechanism 注入HttpSession,确保您获得与当前执行线程相关的HTTPSession

    您还需要确保在 web.xml 中注册 RequestContextListener,以便 Spring 可以注入当前的 HTTPSession

    <listener>  
       <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
    </listener>
    

    【讨论】:

    • 谢谢@Rob。不幸的是,我收到了 IllegalStateException: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread?
    • 我已经更新了我的答案,包括注册 RequestContextListener 应该可以解决您的问题。
    • 我已经测试了另一种解决方案。除了使用 RequestContextListener 之外,您还可以通过添加 @Scope("request") 或编辑 bean 属性来更改范围。
    • 令人惊讶的是,以上都不起作用,仍然得到“无线程绑定”。没有其他想法?谢谢
    • 但似乎 AuthenticationSuccessListener 是单例的,并且似乎 httpSession 可能会导致多用户环境中的不当行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    相关资源
    最近更新 更多