Java:为什么在关闭选项卡或浏览器时不会破坏 http 会话? [英] Java:Why http session is not destroyed when tab or browser is closed?

查看:28
本文介绍了Java:为什么在关闭选项卡或浏览器时不会破坏 http 会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 HttpSessionlistener 的实现

I have the following implementation of HttpSessionlistener

public class SessionListener implements HttpSessionAttributeListener, HttpSessionListener {


public void attributeAdded(HttpSessionBindingEvent event) {
   ...

}


public void attributeRemoved(HttpSessionBindingEvent event) {

    ...
}

public void attributeReplaced(HttpSessionBindingEvent event) {

}

//HttpSesion creation & destruction
public void sessionCreated(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    //log created time


}

public void sessionDestroyed(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    long destroyedTime = System.currentTimeMillis();
    //log destroyed time

}

}

基本上我记录会话创建和销毁时间.但是如果会话很长(默认为 30 分钟),并且用户同时关闭浏览器,

Basically i log the session creation and destruction time. But if the session is long (default to 30 minutes), and user closes browser meanwhile, the

sessionDestroyed 

不叫?

这是为什么?是否有一种解决方法可以准确记录会话被销毁的时间(当用户关闭浏览器时)?这不应该是浏览器的问题,在会话关闭时终止会话吗?

Why is that ? Is there a workaround to log exactly the when the session was destroyed (when user closes the browser)? Should'nt be this be the browser's problem, to kill the session when it is closed ?

有没有我必须实现的接口才能工作?

Is there any interface that i have to implement for this to work ?

谢谢!

推荐答案

服务器如何知道浏览器何时关闭或选项卡何时关闭?此时浏览器不会向服务器发送任何内容.

How would the server know when the browser is closed or the tab closed? At that point the browser doesn't send anything to the server.

这是 HTTP 的基本部分 - 它是一种请求/响应协议,而不是永久开放的对话",您可以在其中判断一方是否离开对话.把它想象成一系列电报而不是一个电话——你不知道你什么时候收到了你将要收到的最后一份电报.

This is a fundamental part of HTTP - it's a request/response protocol, not a "permanently open conversation" where you can tell if one party leaves the conversation. Think of it as a series of telegrams rather than a phone call - and you can't tell when you've received the last telegram you're going to get.

您需要设计自己的方式 - 避免需要知道浏览器何时关闭.有一些丑陋的技巧可以解决这个问题——例如,让 AJAX 使用心跳消息轮询服务器——但改变设计是一个更好的解决方案.

You'll need to design your way round this - to avoid needing to know when the browser has been closed. There are some ugly hacks to work around it - making AJAX poll the server with a heartbeat message, for example - but changing the design is a better solution.

这篇关于Java:为什么在关闭选项卡或浏览器时不会破坏 http 会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆