session到期後自動跳轉到登陸頁

來源:互聯網
上載者:User

標籤:des   style   http   color   java   使用   os   io   

項目需要做一個自動登出的功能,查詢了網上的資料,一開始準備用session監聽做,按照下面方式配置監聽器

1.在項目的web.xml檔案中添加如下代碼:

<!--添加Session監聽器--><listener><listener-class> 監聽器路徑 </listener-class></listener>

2.編寫java類。

public class SessionListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent arg0) {  // session建立時執行  SimpleDateFormat simpleFormat = new SimpleDateFormat("mm-ss-ms");  String nowtimes = simpleFormat.format(new Date());  User u=null;  //System.out.println("執行。。 目前時間:"+nowtimes+"_"+u);  HttpSession ses= arg0.getSession();  String id=ses.getId()+"_"+ses.getCreationTime(); } public void sessionDestroyed(HttpSessionEvent arg0) {  // session失效時執行  SimpleDateFormat simpleFormat = new SimpleDateFormat("mm-ss-ms");  String nowtimes = simpleFormat.format(new Date());   //System.out.println("session失效了。。 結束時間: "+nowtimes); }}

配置完成後等session失效後成功進入sessionDestroyed方法,準備進行頁面跳轉操作,突然發現怎麼寫跳轉,愣住了,繼續上網請教大神,發現這個監聽是做一些後台統計處理的,無法實現頁面跳轉的功能。

只能放棄這方法了,開始使用過濾器實現

1、web.xml中添加過濾器配置

<filter>        <filter-name>sessionFilter</filter-name>        <filter-class>com.orchestrall.web.helper.session.SessionFilter</filter-class></filter><filter-mapping>        <filter-name>sessionFilter</filter-name>        <url-pattern>/actions/*</url-pattern></filter-mapping>

2、建立SessionFilter類,實現Filter介面。

public class SessionFilterimplements Filter {    public void destroy() {        // TODO Auto-generated method stub    }    public void doFilter(ServletRequest request, ServletResponse response,            FilterChain chain) throws IOException, ServletException {        HttpServletRequest httpRequest = (HttpServletRequest) request;        HttpServletResponse httpResponse = (HttpServletResponse) response;        HttpSession session = httpRequest.getSession();        // 登陸url        String loginUrl = httpRequest.getContextPath() + "/admin/login.jsp";        String url = httpRequest.getRequestURI();        String path = url.substring(url.lastIndexOf("/"));        // 逾時處理,ajax請求逾時設定逾時狀態,頁面請求逾時則返回提示並重新導向        if (path.indexOf(".action") != -1                && session.getAttribute("LOGIN_SUCCESS") == null) {            // 判斷是否為ajax請求            if (httpRequest.getHeader("x-requested-with") != null                    && httpRequest.getHeader("x-requested-with")                            .equalsIgnoreCase("XMLHttpRequest")) {                httpResponse.addHeader("sessionstatus", "timeOut");                httpResponse.addHeader("loginPath", loginUrl);                chain.doFilter(request, response);// 不可少,否則請求會出錯            } else {                String str = "<script language=‘javascript‘>alert(‘會話到期,請重新登入‘);"                        + "window.top.location.href=‘"                        + loginUrl                        + "‘;</script>";                response.setContentType("text/html;charset=UTF-8");// 解決中文亂碼                try {                    PrintWriter writer = response.getWriter();                    writer.write(str);                    writer.flush();                    writer.close();                } catch (Exception e) {                    e.printStackTrace();                }            }        } else {            chain.doFilter(request, response);        }    }    @Override    public void init(FilterConfig arg0) throws ServletException {        // TODO Auto-generated method stub    }}

3、用戶端JS,用於ajax請求session逾時

對於jquery

<script type="text/javascript">$(document).ajaxComplete(function(event, xhr, settings) {      if(xhr.getResponseHeader("sessionstatus")=="timeOut"){          if(xhr.getResponseHeader("loginPath")){            alert("會話到期,請重新登陸!");            window.location.replace(xhr.getResponseHeader("loginPath"));          }else{              alert("請求逾時請重新登陸 !");          }      }  });  </script>

對於extjs的ajax請求

Ext.Ajax.on(‘requestcomplete‘,checkUserSessionStatus, this);    function checkUserSessionStatus(conn,response,options){        if(response.getResponseHeader("sessionstatus") == ‘timeout‘){            if(response.getResponseHeader("loginPath")){                alert("會話到期,請重新登陸!");                window.top.location.href = response.getResponseHeader("loginPath");            }else{                alert("請求逾時請重新登陸 !");            }        }    }

如果使某個ajax請求不受全域方法的影響,那麼可以在使用$.ajax()方法時,將參數中的global設定為false,jquery代碼如下:

$.ajax({    url:"test.html",    global:false//不觸發全域ajax事件})

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.