今天发现,当使用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>