Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

spring - How I can get session object from ApplicationListener method

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
    }
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...