项目中,浏览器和服务器之间长时间没有交互,会被超时,但是用户只有在下次尝试连接的时候才会知道已经超时了。总结了一下当前这个项目针对这个问题是怎么做的。
在即将超时的时候,提醒用户,之后通过ajax 发送空消息给服务器以防止服务器将session无效。
下面是核心的代码:
var previousSmSession = null;
var times = 0;
var timer = setInterval("checkSmSession()", 60 * 3000);
var maxTimes = 9;
function checkSmSession()
{
var currentSmSession = getCurrSmSession();
if (currentSmSession != previousSmSession) {
previousSmSession = currentSmSession;
times = 0;
} else {
times++;
if (maxTimes == times) {
this.focus();
var currentCheckingTime = new Date();
currentCheckingTime.setTime(currentCheckingTime.getTime() + 60 * 3000);
var sessionWarningMsg = "Due to inactivity you will be logged out of the system at " + currentCheckingTime.toLocaleString().replace(/^.*?\d{4} /,"") + ". To extend your session click OK.";
var val = confirm(sessionWarningMsg);
if (val) {
times = 0;
refreshSessions();
} else {
// self.location = "/wps/logout.jsp";
}
}
}
}
function getCurrSmSession() {
var allCookies = document.cookie.split(";");
var aCookie = null;
var aCookieName = "";
var aCookieValue = "";
for (var i=0; i<allCookies.length; i++) {
aCookie = allCookies[i].split("=");
aCookieName = aCookie[0].replace(/^\s+|\s+$/g, "");
if (smSessionName == aCookieName) {
if (aCookie.length > 1) {
aCookieValue = unescape(aCookie[1].replace(/^\s+|\s+$/g, ""));
}
break;
}
}
if (i == allCookies.length) {
aCookieValue = null;
}
return aCookieValue;
}
function refreshSessions () {
var dummyUrls = ["/home/FlexKeepAlive.jsp", "/cfi/FlexKeepAlive.jsp"];
for (var i=0; i<dummyUrls.length; i++) {
var aXmlHttp = getXMLHttpObject();
if (null == aXmlHttp) {
alert("AJAX does not work!");
break;
}
aXmlHttp.open("GET", dummyUrls[i]+"?sid="+Math.random(), true);
aXmlHttp.send(null);
}
}
function getXMLHttpObject () {
var xmlHttpObj = null;
try {
xmlHttpObj = new XMLHttpRequest();// Firefox
} catch (e) {
try {
xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP"); //IE
} catch (e) {
xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttpObj;
}