重写 ajax 实现 session 超时跳转到登录页面实例代码
问题:使用window.location.href来跳转页面的时候,后端只需实现一个过滤器就可以在session超时的情况下重定向到登陆页面。但是使用ajax呢?使用ajax来执行会发生302错误,并且页面不可能跳转。下面就针对这个问题来贴上我的前后端代码。
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超时,在此处做处理。 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页
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); //如果请求发生错误,会返回登陆页面源代码,如果源代码里面存在lovnx这个字符串,前端就重定向到登陆页面 var reData = XMLHttpRequest.responseText + ""; if(reData.indexOf('lovnx') != -1) { window.location.href="/manager/login.html" rel="external nofollow" ; return; } } }); return _ajax(_opt); }; });
4、登陆页面添加代码
<input type="hidden" value="lovnx">
相关推荐
houmenghu 2020-11-17
我心似明月 2020-11-09
oraclemch 2020-11-06
ltd00 2020-09-12
康慧欣 2020-09-10
waveclouds 2020-09-04
蓝色深海 2020-09-15
jincheng 2020-09-01
思君夜未眠 2020-08-25
取个好名字真难 2020-08-06
歆萌 2020-08-03
阳光之吻 2020-08-03
婷婷小屋 2020-07-28
solarspot 2020-07-28
MLXY 2020-07-26
dxbjfu0 2020-07-26
songbinxu 2020-07-19
83520298 2020-07-06