我如何从ApplicationListener方法获取会话对象

时间:2013-11-05 16:39:29

标签: spring spring-mvc spring-security

我想在成功进行用户身份验证后将对象添加到HttpSession请不要向SavedRequestAwareAuthenticationSuccessHandler建议解决方案,因为在此应用中由于某种原因应用程序正在进行原始请求

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

1 个答案:

答案 0 :(得分:8)

据我所知,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>