我需要终止会话,并在浏览器关闭或选项卡关闭后执行一个功能



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

以下是会话被破坏时执行的代码。

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

但是,我不想等到会议结束。我需要在浏览器关闭后执行此代码。希望有人能帮我摆脱困境。

谢谢

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

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

或使用JS

window.onbeforeunload = function() {...

然后,您可以启动一些ajax来调用服务器端代码。

使用检测浏览器的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
});
});

更新

如何区分浏览器关闭和刷新事件??

最新更新