問題:使用window.location.href來跳轉頁面的時候,後端只需實現一個過濾器就能夠在session超時的狀況下重定向到登錄頁面。可是使用ajax呢?使用ajax來執行會發生302錯誤,而且頁面不可能跳轉。下面就針對這個問題來貼上個人先後端代碼。html
import java.io.IOException;
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;
public class SessionFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String requestUri = request.getRequestURI();
if (requestUri.indexOf("/login.html") > -1 || requestUri.indexOf("/login") > -1) {
return ;
}
HttpSession session = request.getSession(false);
if (session == null) {
// 若是是session超時,在此處作處理。
response.sendRedirect(request.getContextPath() + "/login.html");
return ;
}
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
e.printStackTrace();
}
return ;
}
}複製代碼
<filter>
<filter-name>sessionFilter</filter-name>
<filter-class>com.lovnx.filter.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>複製代碼
注意:此段代碼放在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="/login.html";
return;
}
}
});
return _ajax(_opt);
};
});複製代碼
<input type="hidden" value="lovnx">複製代碼