aspose file tools*
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes HttpSessionListener Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "HttpSessionListener" Watch "HttpSessionListener" New topic
Author

HttpSessionListener

ashi mu
Greenhorn

Joined: Oct 21, 2003
Posts: 5
I would like to perform certain functions(certain housekeeping activities like flushing cache..., for now lets say i want to print a default message), when a user logs out. Can somebody brief me and give me a code sample (listener impl,jsp,xml) on how to do that using HttpSessionlistener.
Thanks a lot.
Shreyas Reddy
Ranch Hand

Joined: Oct 09, 2003
Posts: 49
If you are invalidating the session when a user logsout, you can do the logging in sessionDestroyed() method of HttpSessionListener implementation class.
ashi mu
Greenhorn

Joined: Oct 21, 2003
Posts: 5
Can somebody give me a code sample (listener impl,jsp,xml) on how to do that when user logs out or closes browser.
Thanks a lot.
Shreyas Reddy
Ranch Hand

Joined: Oct 09, 2003
Posts: 49
Here is the sample listener implementation :

In your JSP/servlet you should add the username/loginname of the user as an attribute called "user" to the session.
In your web.xml add

I hope this helps.
ashi mu
Greenhorn

Joined: Oct 21, 2003
Posts: 5
Thank you, that really helped.
But I have a doubt.
I understand that the sessionDestroyed() method is invoked after the session is invalidated. If thats the case, how is it possible to invoke getAttribute() methods on the session object. I would need attributes from the session, to clear cache. So should I consider HttpSessionAttributeListener. Please explain with sample source code.
Thanks in advance.
Dong Shing
Greenhorn

Joined: Oct 24, 2003
Posts: 12
That is a good question.
In your case, if you'd like to do some clean-up job after a session is invalidated, you may not use HttpSessionListener because the attributes bound in it also get purged. You should resort to HttpSessionBindingListener. First wrap up the object you'd like to bind to the session, such as database connection, in HttpSessionBindingListener interface, and then implements valueBound and valueUnbound method. When the session is invalidated, all the objects bound to the session would get removed. At this moment, the object that implements HttpSessionBindingListener will get the notification about the removal by being invoked on method valueUnbound. Then you could clean up the resources here.
import javax.servlet.*;
import javax.servlet.http.*;
public class DBConnectionWrapper
implements HttpSessionBindingListener {
public void valueBound(HttpSessionBindingEvent event) {
//implment your init duty here
}
public void valueUnbound(HttpSessionBindingEvent event) {
//implement your cleanup duty here.
}
}
 
 
subject: HttpSessionListener