今天發現,當使用Ajax請求時,若是後臺進行重定向到其餘頁面時是沒法成功的,只能在瀏覽器地址欄輸入纔可以實現重定向。前端
Ajax默認就是不支持重定向的,它是局部刷新,不從新加載頁面。ajax
須要實現的功能是,後臺網關攔截請求,看請求中是否存在token.若是不存在就跳轉到登陸頁面。由於大多數請求都是使用Ajax.一開始發現沒法進行重定向,每次都是返回到Ajax的結果處理函數。最終的解決辦法以下,須要後臺和前端進行處理。瀏覽器
/** *功能描述 * @author lgj * @Description 重定向工具類 * @date 2/27/19 */ @Slf4j public class RedirecUtil { /** *功能描述 * @author lgj * @Description 重定向 * @date 2/27/19 * @param: * @return: * */ public static void redirect(RequestContext ctx, String redirectUrl){ try{ //若是是Ajax請求 if("XMLHttpRequest".equals(ctx.getRequest().getHeader("X-Requested-With"))){ log.debug("ajax redirect"); sendRedirect(ctx.getResponse(),redirectUrl); } //若是是瀏覽器地址欄請求 else { log.debug("normal redirect "); ctx.getResponse().sendRedirect(redirectUrl); } } catch(Exception ex){ ex.printStackTrace(); } } /** *功能描述 * @author lgj * @Description Ajax請求時重定向處理 * @date 2/27/19 * @param: * @return: * */ private static void sendRedirect(HttpServletResponse response, String redirectUrl){ try {
//這裏並非設置跳轉頁面,而是將重定向的地址發給前端,讓前端執行重定向 //設置跳轉地址 response.setHeader("redirectUrl", redirectUrl); //設置跳轉使能 response.setHeader("enableRedirect","true"); response.flushBuffer(); } catch (IOException ex) { log.error("Could not redirect to: " + redirectUrl, ex); } } }
$.ajax({ type: "post", url: "/auth/token/check", success: function(data,status){ console.log("/token/check 返回 status : "+status) },
//請求完成調用 (XHR, TS){ console.log("complete"); var url = XHR.getResponseHeader("redirectUrl"); console.log("redirectUrl = " + url); var enable = XHR.getResponseHeader("enaleRedirect");
console.log("enableRedirect = " + enable);
if((enable == "true") && (url != "")){
var win = window;
while(win != win.top){
win = win.top;
}
win.location.href = url;
}
},
});
})
可是上面有個問題就是,每一個ajax都須要編寫 comlete 方法,代碼複用率低。函數
ajax請求工具
$("#NON-TOKEN").click(function () { $.ajax({ type: "post", url: "/auth/token/check", success: function(data,status){ console.log("/token/check 返回 status : "+status) }, });
全局處理post
注意這參數(event, xhr, settings)不能少,不然會報錯。url
//每個Ajax 請求完成以後都會執行。
$(document).ajaxComplete(function (event, xhr, settings) { console.log("ajaxComplete ") redirectHandle(xhr); })
function redirectHandle(xhr) {
//獲取後臺返回的參數 var url = xhr.getResponseHeader("redirectUrl"); console.log("redirectUrl = " + url); var enable = xhr.getResponseHeader("enableRedirect"); if((enable == "true") && (url != "")){ var win = window; while(win != win.top){ win = win.top; } win.location.href = url; }
}
function redirectHandle(xhr) { var url = xhr.getResponseHeader("redirectUrl"); console.log("redirectUrl = " + url); var enable = xhr.getResponseHeader("enableRedirect"); if((enable == "true") && (url != "")){ var win = window; while(win != win.top){ win = win.top; } win.location.href = url; } } $(function () { $(document).ajaxComplete(function (event, xhr, settings) { console.log("ajaxComplete adffdafadsaf") redirectHandle(xhr); }) })
引入js文件,src根據據實際狀況設置。spa
<script src="/common/redirect.js"></script>