Listening to when the user session is ended in a JSF managed bean
Asked Answered
B

3

6

Is it possible to do something like this: When a user session starts I read a certain integral attribute from the database. As the user performs certain activities in this session, I update that variable(stored in session) & when the session ends, then I finally store that value to the DB.

My question is how do I identify using the JSF framework if the user session has ended & I should then store the value back to DB?

Bandsman answered 5/6, 2011 at 5:50 Comment(0)
U
10

Apart from the HttpSessionListener, you can use a session scoped managed bean for this. You use @PostConstruct (or just the bean's constructor) and @PreDestroy annotations to hook on session creation and destroy

@ManagedBean
@SessionScoped
public class SessionManager {

    @PostConstruct
    public void sessionInitialized() {
        // ...
    }

    @PreDestroy
    public void sessionDestroyed() {
        // ...
    }

}

The only requirement is that this bean is referenced in a JSF page or as @ManagedProperty of any request scoped bean. Otherwise it won't get created. But in your case this should be no problem as you're apparently already using a session scoped managed bean, just adding a @PreDestroy method ought to be sufficient.

Unanimity answered 5/6, 2011 at 11:14 Comment(2)
I am trying this second approach as it looks good. Plus I need to be able to get a handle on ejbs and entity manager which seems to only be available from managed beans in JSF (as opposed to the HttpSessionListener). I make the sessionscoped managedbean a managedproperty of my login handling requestscoped bean so that it comes into scope when the user logs in. The problem I'm having is that it seems the method I marked @PreDestroy gets called as the login bean goes out of scope (i.e. when the login method returns). So my code is firing early. Any ideas on why this might happen?Tabasco
mkyong.com/servlet/…Preordain
I
5

My question is how do I identify using the JSF framework if the user session has ended & I should then store the value back to DB?

The JSF framework does not have a separate concept of a session; it uses the underlying session management features of the Servlet specification.

You would have to create a HttpSessionListener that provides hooks for you to capture the session creation and destruction events, where you can read the value and store it back into the DB.

Introversion answered 5/6, 2011 at 6:18 Comment(0)
N
2

HttpSessionListener, or if you need Dependency Injection for that save, you might use @PostConstruct & @PreDestroy. Remember that the session is destroyed when you call invalidate() or after session timeout, not when the user closes the browser. Why do you use Session Scope anyway, Conversation Scope might fit you better.

Nonalcoholic answered 5/6, 2011 at 12:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.