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


问题内容

我想HttpSession在成功的用户身份验证后添加对象。请不要提出解决方案,SavedRequestAwareAuthenticationSuccessHandler因为在此应用中由于某种原因应用正在忽略原始请求。

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

问题答案:

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

因此,要获得对当前HttpSession实例的引用:

public class AuthenticationSuccessListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {

@Autowired
private HttpSession httpSession;

        @Override
        public void onApplicationEvent(InteractiveAuthenticationSuccessEvent e) {
               //adding object to HttpSession
        }
}

Spring将HttpSession使用其作用域代理机制注入,以确保您HTTPSession与当前执行线程相关。

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

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