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

win*_*eld 4 spring spring-mvc spring-security

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

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

Rob*_*ake 9

据我所知,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
        }
}
Run Code Online (Sandbox Code Playgroud)

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

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

<listener>  
   <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
</listener>
Run Code Online (Sandbox Code Playgroud)

  • 令人惊讶的是,上述所有工作都没有,仍然是"没有线程限制".没有其他想法?谢谢 (3认同)