onunload和onbeforeunload调用AJAX来注销session!


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
   
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
   
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script>
     var xmlHttp;
     /**
   *名称:createXMLHttpRequest()
   *功能:创建XMLHttpRequest对象
   *作者 luan
   *返回:无
   */
     function createXMLHttpRequest()
     {
      //IE
      if (window.ActiveXObject)
      {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      //Other
      else if (window.XMLHttpRequest)
      {
       xmlHttp = new XMLHttpRequest();
      }
     }
     /**
   *名称:unloadDestorySession()
   *功能:当点击关闭的时候调用该方法来销毁session
   *作者 luan
   *返回:无
   */
        function unloadDestorySession()
     {
      //首先要判断是要关闭页面还是要刷新页面
      //关闭页面要销毁session而刷新页面要保留session
       if(window.event.clientX < 0 && window.event.clientY < 0 || window.event.altKey)
       {
     try{
     //关闭
     createXMLHttpRequest();
        var url = "<%=basePath%>" + "destorysession.jsp";
        xmlHttp.open("POST", url, false);
        xmlHttp.send(null);
        var result = xmlHttp.responseText;
     }
     catch(e)
     {
      //异常处理,防止服务器关闭后,解决用户关闭页面产生脚本错误!
     }
    }
     }
    </script>
  </head>
 
  <body οnunlοad="unloadDestorySession()">
    这是一个操作的主页面,点击关闭的时候会调用unloadDestorySession()方法!<BR>
    由于我已经判断了关闭事件,因此不需要再使用隐藏域来记录页面转向或是刷新的操作了!可以像正常情况来操作页面!<br>
    
    <a href="TestDestorySession.jsp">销毁创建session</a><BR>
    使用说明:<BR>
     用于不知道使用何种底层框架,因此将session销毁的动作放在jsp中来执行,保证了通用性!使用的时候必须调用destorysession.jsp,<BR>
     注意jsp的路径,如果修改该jsp的路径必须保证unloadDestorySession()中的url的路径正确!
    <P>
    解决了以下问题:<BR>
     1 用户刷新页面时候也会调用onunload事件,但此时应当保存session状态。 表现【 用户点击“刷新”或“F5” 已经解决】<BR>
     2 点击关闭销毁session状态。 表现【 用户点击“关闭”或“ALT+F4” 销毁session状态 已经解决】<BR>
     3 在主页面上操作,当转向其他页面的时候也调用onunload事件,此时也要保存session状态。  表现【点击页面上的链接 保存session状态 已经解决】<BR>
    </P> 
    cookie例子<a href="servlet/CookieServlet">cookie例子</a><BR>
  </body>
</html>

 

 <html>
 <body>
 <script>
 function LeaveWin(){
 event.returnValue="要闭吗";
 }
 window.οnbefοreunlοad=LeaveWin;
 </script>
 </body>
 </html>
  

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值