Session過期後自動跳到登入頁面的實例代碼
最近做了一個專案有需求,要實現自動登入功能,透過查閱相關資料,打算用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>
登入後複製
如果使某個ajax請求不受全域方法的影響,那麼可以在使用$.ajax()方法時,將參數中的global設定為false,jquery程式碼如下:
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("请求超时请重新登陆 !"); } } }
登入後複製
以上所述是小編給大家介紹的Session過期後自動跳到登入頁面的實例代碼,希望對大家有幫助,如果大家想了解更多內容請關注PHP中文網!
更多Session過期後自動跳到登入頁面的實例代碼相關文章請關注PHP中文網!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章
Windows 11 KB5054979中的新功能以及如何解決更新問題
4 週前
By DDD
如何修復KB5055523無法在Windows 11中安裝?
3 週前
By DDD
如何修復KB5055518無法在Windows 10中安裝?
3 週前
By DDD
R.E.P.O.的每個敵人和怪物的力量水平
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
藍王子:如何到達地下室
3 週前
By DDD

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)