【代码笔记】服务器检查浏览器是否关闭

之前用Session保存登录信息,logout清除Session信息,但是会出现关闭浏览器无法清除Session,所以使用服务器来检测浏览器是否关闭。

原理:

使用ajax+线程。

具体思路:

1.在页面使用js定时器(setInterval)来定时使用ajax的post来向服务器发出消息。

2.在服务器端每次接收到消息,将Session的alive的值+1,如果是第一次接收到消息,则将Session新建一个attribute,并启动检查线程。

3.检查线程则是每过一段时间检查一次Session,检查alive的值是否改变。如果没改变说明浏览器已经关闭。

具体实现代码:

JS文件:

function start() {
			setInterval(function() {
				$.post("alive.do", {}, null)
			}, 1000);
}

JAVA服务器文件:

if (action.equals("alive")) {
			int i = 0;
			if (session.getAttribute("alive") != null) {
				i = (Integer) session.getAttribute("alive");
			} else {
				Thread t1 = new Thread(new PostAlive(session));
				t1.start();
				// System.out.println("heart");
			}
			i++;
			session.setAttribute("alive", i);
		}

JAVA线程文件:

package thread;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PostAlive implements Runnable {

	private HttpSession session = null;
	private int i = -1;
	private boolean useful = true;

	public void setUseful(boolean useful) {
		this.useful = useful;
	}

	public PostAlive(HttpSession session) {
		this.session = session;
	}

	public void run() {
		// TODO Auto-generated method stub
		while (useful) {
			synchronized (session) {
				try {
					int tmp = (Integer) session.getAttribute("alive");
					if (tmp == i) {
						// System.out.println(tmp+"______");
						useful = false;
						if (session.getAttribute("rem") != null) {
							return ;
						}
						synchronized (this) {
							session.removeAttribute("pwd");
							session.removeAttribute("user");
							session.removeAttribute("alive");
							session.invalidate();
						}
						return;
					}
					i = tmp;
				} catch (Exception e) {
					useful = false;
				}
			}
			try {
				Thread.sleep(30000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值