之前用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();
}
}
}
}