File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Session Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Session" Watch "Session" New topic


Raj Joe
Ranch Hand

Joined: Oct 15, 2004
Posts: 41
How do i clear the http session data when the user closes the browser.
Can i invalidate a user session when the user closes the browser.
Praful Thakare
Ranch Hand

Joined: Feb 10, 2001
Posts: 642
I dont know the exact code but u can do it as follows

1 handel windows (browser)close event
2 call a javascript function on it and send request to some jsp
on server which will invalidate the session.


All desirable things in life are either illegal, banned, expensive or married to someone else !!!
Shailesh Chandra
Ranch Hand

Joined: Aug 13, 2004
Posts: 1082

I dont think handling the close event of browser is very efficient.

eg: I press CTRL + N during any session and new window gets open with same session. I perform any operation on new window same time old window is open.

but closing any window will kill my session, and being a user I will not like it.
[ October 27, 2004: Message edited by: Shailesh Chandra ]

Gravitation cannot be held responsible for people falling in love ~ Albert Einstein
Sonny Gill
Ranch Hand

Joined: Feb 02, 2002
Posts: 1211

You cant use Javascript function to invalidate session when the user closes the browser.

The cross browser JavaScript you can possibly use is the onUnload() event. This event gets fired whenever the current page being shown is about to be changed. Most browsers fire it when you close the browser, but it will also be fired when you move from one page to next. So, you cant reliably use it to detect a browser being closed.

The best thing to do is to set the session time out appropriately for your web app. It has been discussed many times before.
Try doing a google search of Javaranch forums
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Hi folks,

shouldn't be the javascript soluiton. ofcourse you should do that always. but again its on client-end. Moreover, javascript may vary browser to browser.

its better to use HttpSessionListener. and invalidate the session on logout and session-timeout. it will definitely work in any case. but ofcourse session-timeout might not be the real logout time for the user. you can use javascript solution along this one.

I agree. Here's the link:
subject: Session
It's not a secret anymore!