这是防止Java应用程序的浏览器选项卡之间的会话剪切的解决方案。这将适用于IE(JSP / Servlet)
- 在您的第一个JSP页面中,onload事件调用一个servlet(ajex调用)以在会话中设置“ window.title”和事件跟踪器(只是一个整数变量,第一次被设置为0)。
- 确保没有其他页面设置window.title
- 一旦页面加载完成,所有页面(包括第一页)都会添加一个Java脚本来检查窗口标题。如果找不到标题,则关闭当前页面/选项卡(请确保在发生这种情况时撤消“ window.unload”功能)
- 设置页面window.onunload Java脚本事件(针对所有页面)以捕获页面刷新事件,如果页面已刷新,则调用servlet重置事件跟踪器。
1)首页JS
BODY onload="javascript:initPageLoad()"
function initPageLoad() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var serverResponse = xmlhttp.responseText;
top.document.title=serverResponse;
}
};
xmlhttp.open("GET", 'data.do', true);
xmlhttp.send();
}
2)所有页面通用的JS
window.onunload = function() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var serverResponse = xmlhttp.responseText;
}
};
xmlhttp.open("GET", 'data.do?reset=true', true);
xmlhttp.send();
}
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
init();
clearInterval(readyStateCheckInterval);
}}, 10);
function init(){
if(document.title==""){
window.onunload=function() {};
window.open('', '_self', ''); window.close();
}
}
3)web.xml-servlet映射
<servlet-mapping>
<servlet-name>myAction</servlet-name>
<url-pattern>/data.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>myAction</servlet-name>
<servlet-class>xx.xxx.MyAction</servlet-class>
</servlet>
4)servlet代码
public class MyAction extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Integer sessionCount = (Integer) request.getSession().getAttribute(
"sessionCount");
PrintWriter out = response.getWriter();
Boolean reset = Boolean.valueOf(request.getParameter("reset"));
if (reset)
sessionCount = new Integer(0);
else {
if (sessionCount == null || sessionCount == 0) {
out.println("hello Title");
sessionCount = new Integer(0);
}
sessionCount++;
}
request.getSession().setAttribute("sessionCount", sessionCount);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "private, no-store, no-cache, must- revalidate");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
}
}