How I can get session object from ApplicationListener method

心已入冬 提交于 2019-12-29 07:09:19

问题


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
    }
} 

回答1:


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.

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 will inject the HttpSession using its scoped proxy mechanism ensuring that you get the HTTPSession relevant to the current thread of execution.

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>


来源:https://stackoverflow.com/questions/19794115/how-i-can-get-session-object-from-applicationlistener-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!