登录失效后ajax访问后台问题解决

由于后台加入了权限管理,登录失效后访问后台会发生重定向,而ajax访问的无法跳转到登录页面。

1.通过在权限管理器中加入判断是否是ajax访问来区分两种请求。

//ajax请求方式会获取到 XMLHttpRequest ,其他请求方式没有这个请求头
String requestType = request.getHeader("X-Requested-With");
if(StringUtil.isNotEmpty(requestType) && "XMLHttpRequest".equals(requestType)) {
    String jsonStr = "{\"code\":\"not_login\",\"msg\":\"没有登录\"}";
    UtilUrl.setJsonResponse(response, jsonStr);
}else {
	request.setAttribute("referer", url);
    request.getRequestDispatcher("/jsp/user/login.jsp").forward(request, response);
}
/**
* 设置json返回数据
 * @param request
 * @return
 */
public static void setJsonResponse(HttpServletResponse response, String jsonStr){
    response.setCharacterEncoding("UTF-8");  
    response.setContentType("application/json; charset=utf-8");  
    PrintWriter out = null; 
    try {  
        out = response.getWriter();  
        out.append(jsonStr);  
    } catch (Exception e) {  
        log.error("设置json返回数据失败:"+e.getMessage());
    } finally {  
        if (out != null) {  
            out.close();  
        }  
    }
}

2.修改jquery ajax源码 当获取到返回参数是json格式,并且code值为not_login的时候自动刷新页面,刷新页面后是否执行登录操作由后台处理。

//权限拦截自动跳转
if(status == 200){
	try{
		var obj = eval('(' + responses.text + ')');
		if(obj.code=='not_login'){
			window.location.reload();
			return false;
		}
	}catch(e){
		
	}
}

或者在jquery.js文件最后添加ajax回调函数

//ajax完成时回调函数
$(document).ajaxComplete(function(event, xhr, settings) {
	if(xhr.responseJSON && xhr.responseJSON.code == "998"){
		window.location.reload();
	}
});

jquery代码添加位置 (以jquery 2.1.4为例) 第8210行 if 判断内
// Get response data
if ( responses ) {
登录失效后ajax访问后台问题解决_第1张图片

你可能感兴趣的:(登录失效后ajax访问后台问题解决)