Java:Why http session is not destroyed when tab or browser is closed?

后端 未结 8 1715
-上瘾入骨i
-上瘾入骨i 2020-12-06 00:54

I have the following implementation of HttpSessionlistener

public class SessionListener implements HttpSessionAttributeListener, HttpSessionListener {


publ         


        
8条回答
  •  佛祖请我去吃肉
    2020-12-06 01:14

    NOTE: As jwenting commented below, this it's not 100% safe at all. If the the onunload event does not get triggered by a closing event of the browser tab or window, then this would fail.

    I had the same problem, and solve it using an intrusive JavaScript event:

    window.onunload
    

    Let me briefly explain, lets say you have a JavaScript function that post, using jQuery, the current Session ID to that Servlet to invalidate it, like this:

    function safeexit(){
       $.post("/SessionKillServlet", { SID = <%=session.getId()%> }, function(data){});
    }
    

    To call that function, you just need to bind it like these:

    window.onunload =  safeexit;  //without the ()
    

    Now, safeexit method will be called when the TAB or BROWSER WINDOW gets closed (or in a redirection).

提交回复
热议问题