問題:使用window.location.href來跳轉(zhuǎn)頁(yè)面的時(shí)候,后端只需實(shí)現(xiàn)一個(gè)過濾器就可以在session超時(shí)的情況下重定向到登陸頁(yè)面。但是使用ajax呢?使用ajax來執(zhí)行會(huì)發(fā)生302錯(cuò)誤,并且頁(yè)面不可能跳轉(zhuǎn)。下面就針對(duì)這個(gè)問題來貼上我的前后端代碼。
1、session過濾器
import java.io.IOException; <p style="text-align: center"><img alt=""import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; <p style="text-align: center"><img alt=""public class SessionFilter implements Filter { <p style="text-align: center"><img alt="" public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; <p style="text-align: center"><img alt="" String requestUri = request.getRequestURI(); <p style="text-align: center"><img alt="" if (requestUri.indexOf("/login.html") > 0 || requestUri.indexOf("/system/login") > 0) { return ; } <p style="text-align: center"><img alt="" HttpSession session = request.getSession(false); <p style="text-align: center"><img alt="" if (session == null) { // 如果是session超時(shí),在此處做處理。 response.sendRedirect(request.getContextPath() + "/login.html"); return ; } try { filterChain.doFilter(request, response); } catch (Exception e) { e.printStackTrace(); } return ; } }
2、web.xml添加配置:
<filter> <filter-name>sessionFilter</filter-name> <filter-class>com.manager.filter.SessionFilter</filter-class> </filter> <filter-mapping> <filter-name>sessionFilter</filter-name> <url-pattern>/manager/*</url-pattern> </filter-mapping>
*3、重寫ajax
注意:此段代碼放在index頁(yè)
jQuery(function($){ var _ajax=$.ajax; $.ajax=function(opt){ var _success = opt && opt.success || function(a, b){}; var _opt = $.extend(opt, { success:function(data, textStatus){ _success(data, textStatus); }, error:function(XMLHttpRequest, textStatus, errorThrown){ //alert(XMLHttpRequest.responseText); //如果請(qǐng)求發(fā)生錯(cuò)誤,會(huì)返回登陸頁(yè)面源代碼,如果源代碼里面存在lovnx這個(gè)字符串,前端就重定向到登陸頁(yè)面 var reData = XMLHttpRequest.responseText + ""; if(reData.indexOf('lovnx') != -1) { window.location.href="/manager/login.html" rel="external nofollow" ; return; } } }); return _ajax(_opt); }; });
4、登陸頁(yè)面添加代碼
<input type="hidden" value="lovnx">
以上所述是小編給大家介紹的重寫 ajax 實(shí)現(xiàn) session 超時(shí)跳轉(zhuǎn)到登錄頁(yè)面實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com