I need to kill a session and perform one function after closing the browser or closing the tab

I want to kill a session after closing the browser or closing the tab. And I need to make one connection to the database after the session, using Session Listener.But, for this I need to wait until the session is destroyed.

Here is the code that executes when the session is destroyed.

public void sessionDestroyed(HttpSessionEvent event) { synchronized (this) { //System.out.println("deletion"); ServletContext application = event.getSession().getServletContext(); sessionCount = (Integer) application.getAttribute("SESSION_COUNT"); application.setAttribute("SESSION_COUNT", sessionCount=sessionCount - 1); //application.setAttribute("SESSION_COUNT", --sessionCount); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("" + e); } Connection connection = null; try { connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5", "root", ""); Statement st = connection.createStatement(); st.executeUpdate("update adminlogin set Password='admin' where Username='admin'"); } catch (SQLException e) { e.printStackTrace(); } } System.out.println("Session Destroyed: " + event.getSession().getId()); System.out.println("Total Sessions after delete: " + sessionCount); } 

But I do not want to wait until the session is destroyed. I need to make this code after the browser gets closer. Hope someone gets me out of this.

thanks

+6
source share
2 answers

If you use jquery , you can listen to the unload event

https://api.jquery.com/unload/

or using js

  window.onbeforeunload = function() {... 

Then from couse you can run some ajax to call the server side code.

+2
source

Close Event Browser Detection and Invalid Session Using

 if(session!=null) { session.invalidate(); } 

How to detect a browser Close an event?

 $(document).ready(function() { $(window).bind("beforeunload", function() { return confirm("Do you really want to close?"); // here you can invalidate }); }); 

Update

How to distinguish between browser close event and update?

+2
source

Source: https://habr.com/ru/post/985043/


All Articles