Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How we call logout servlet on browser close event

Tags:

jsp

How can I handle the close event of a browser to trigger a logout?

like image 240
DJJ Avatar asked Oct 21 '10 10:10

DJJ


People also ask

How do you end a session in Servlet?

Deleting Session Data Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with a particular key. Delete the whole session − You can call public void invalidate() method to discard an entire session.

How do you end a session in Java?

"Closing" a session happens by invalidate() method. It destroys the entire session and unbinds all of the attributes. Any next HTTP request will result in a fresh new session.

What is session in JSP Servlet?

Jakarta EE/Java JEE 8 Web Development(Servlet, JSP and JDBC) The session object is used to track a client session between client requests. JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across. a one-page request or. visit to a website or.


2 Answers

I've searched for a consistent solution to this problem some time ago, and my decision was to handle the situation without believing the browser or the user.

You can't for sure know if a user is leaving your page and when, and even if you use 'onunload', you may not get the event before the browser closes or leaves your page. And browser crashes won't give you any kind of signal, so believing you know the user is still viewing you page and may take any further action is flawed.

The best you can do about logging out an user is put a fitting session timeout, and if you need further control, you may try adding AJAX calls on critical pages with 'I'm alive' signals, and then logging out users that are not responding anymore (that would require AJAX/JS enabled browser and may exclude potential users).

like image 122
mdrg Avatar answered Sep 22 '22 17:09

mdrg


You're looking for the onunload:

window.onunload = function() {
  // check the window is closed (see point 1 below)
  // do log out
}

There are 2 problems with this:

  1. It's called whenever the user navigates away from the page, refreshes, or generally unloads as well as when the browser window is closed.
  2. There doesn't seem to be a consistent behaviour between browsers.

I recommend using a different approach.

like image 37
EMMERICH Avatar answered Sep 22 '22 17:09

EMMERICH