【问题标题】:I need to kill session and do one function after browser close or tab close我需要在浏览器关闭或标签关闭后终止会话并执行一项功能
【发布时间】:2015-06-18 10:42:18
【问题描述】:

我想在浏览器关闭或选项卡关闭后终止会话。并且我需要在会话过期后使用 Session Listener 进行一次数据库连接。但是,为此我需要等到会话销毁。

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

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

但是,我不想等到会话销毁。我需要在浏览器关闭后执行此代码。希望有人能帮我解决这个问题。

谢谢

【问题讨论】:

    标签: java javascript session


    【解决方案1】:

    如果你使用jquery,你可以监听unload事件

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

    或者使用JS

     window.onbeforeunload = function() {...
    

    那么你当然可以触发一些 ajax 来调用服务器端代码。

    【讨论】:

    • 是的,我也尝试过使用 onbeforeunload 函数,但它不仅针对关闭事件执行,还针对刷新按钮执行。
    • 是的,这是真的。它只知道你要离开页面
    • 是的,我离开页面时不会使只有我的问题的会话无效
    • 您更新的链接很好,但我可以使用会话超时本身来实现。如果假设用户没有与浏览器交互几分钟意味着它过期知道我不想要那个
    • for.ex:如果我给会议时间,意味着我可以实现我所需要的。但会话不会在用户无效或关闭浏览器之前过期
    【解决方案2】:

    使用

    检测浏览器的Close EventInvalidate Session
    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 ??

    【讨论】:

    • Neeraj 我试过这段代码,但它也执行窗口刷新。我只需要标签关闭或窗口关闭事件而不是刷新事件
    • 查看更新的答案,希望对您有所帮助!!
    • 您更新的链接很好,但我可以使用会话超时来实现。如果假设用户没有与浏览器交互几分钟意味着它过期知道我不想要那个
    • for.ex:如果我给会议时间,意味着我可以实现我所需要的。但会话不会在用户无效或关闭浏览器之前过期
    猜你喜欢
    • 1970-01-01
    • 2010-12-27
    • 2015-04-23
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2020-07-17
    相关资源
    最近更新 更多