我需要杀死会话并在浏览器关闭或制表符关闭后执行一个功能

时间:2015-04-13 07:27:48

标签: java javascript session

我想在浏览器关闭或标签关闭后终止会话。我需要在会话到期后使用Session Listener.But进行一次数据库连接,为此我需要等到会话销毁。

以下是会话销毁时执行的代码。

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);
    }

但是,我不想等到会话破坏。我需要在浏览器关闭后执行此代码。希望有人能让我离开这个。

谢谢

2 个答案:

答案 0 :(得分:2)

如果您使用jquery,则可以收听unload事件

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

或使用JS

 window.onbeforeunload = function() {...

然后你可以发一些ajax来调用服务器端代码。

答案 1 :(得分:2)

使用

检测浏览器 Close Event 使会话无效
if(session!=null) { 
session.invalidate();   
}   

如何检测浏览器关闭事件?

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

<强>更新

How to differentiate between Browser Close and Refresh Event ??