Jonathan,

This seems to work, thank you. It doesn't seem bad at all. It's important to note, though, that this use of the HttpSessionListener will only work if using servlet specification 2.4. Containers implementing 2.3 will invalidate the session (and remove all attributes) first, and then notify the listener. In that case, you will either have to use an HttpSessionAttributeListener or an HttpSessionBindingListener. Fortunately, my current project is already at 2.4, so your suggestion is working great! :)

> It has the advantage that you can
> still persist the user data even if the session simply expires
> rather than only when the user clicks on something to logout.

Precisely the idea.

Regards,

Jeff Bischoff
Kenneth L Kurz & Assoc, Inc.

Jonathan Harley wrote:
Jeff Bischoff wrote:
I am looking for a JSF-based way to detect when a session is expiring and run some code before it dies. Specifically, I am writing a myfaces/tomahawk web application, and wish to save some user state information to the database when the session expires. When they next log in, they will have their previous state restored.

I have an ugly solution to this problem from my last Struts app, but I'm looking for something cleaner. In Struts, when someone logged in, I manually added a bean to the session with a specific attribute name (e.g. "USER"). Then I registered a HttpSessionAttributeListener, and in the attributeRemoved method I compared the name of the attribute being removed to the bean's name. If they matched, then the bean was being removed from the session, meaning this user was logging off.

It was normal in my Struts app to manually get and set request and session attributes, but using JSF has obviated the need for such mess and clutter... until now. So I would really like to keep things clean, and find a better, JSF-oriented way. Any ideas?

Are JSF managed-beans guaranteed to have a certain name, when their session attribute is removed? Maybe I could still do a comparison in the listener, despite never explicitly adding anything to the session directly...

The session attribute name of a JSF managed bean is exactly the
name you set in the faces config file. You don't need to
explicitly set and get them or manually remove them from the
session. You can just implement HttpSessionListener and catch
sessionDestroyed events. From the event you can get the session,
and from the session the attribute with the user data to be saved.

I don't think this is particularly ugly, and it is the standard
servlet-API way of doing it. It has the advantage that you can
still persist the user data even if the session simply expires
rather than only when the user clicks on something to logout.

J.


Reply via email to