解决拦截器对ajax请求的的拦截
Posted zouhong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决拦截器对ajax请求的的拦截相关的知识,希望对你有一定的参考价值。
1、java后端代码
package com.yb.fw.app.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSONObject; import com.yb.fw.core.helper.FwConstant; @Component public class FrontAuthorityInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String url = request.getRequestURI(); String requestedWith =request.getHeader("X-Requested-With"); if(url.indexOf("/store/login.do")>=0) { return true; }else if(url.indexOf("/store/land.do")>=0) { return true; } HttpSession session = request.getSession(); if(session.getAttribute(FwConstant.SESSION_USERINFO) == null) { if("XMLHttpRequest".equals(requestedWith)){ System.out.println("请求被拦截,跳转到登录页面");//控制台提示用 JSONObject res = new JSONObject(); res.put("message","IsAjax"); response.getWriter().append(res.toString()); }else{ response.sendRedirect(request.getContextPath()+"/people/toLogin.do"); } return false; }else return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { } }
(1)、判断 String XRequested =request.getHeader("X-Requested-With") 的值,目的是判断是否是ajax请求。
(2)、组装json数据
JSONObject res = new JSONObject(); res.put("message","IsAjax"); response.getWriter().append(res.toString());
判断的方式存在两种方式:
(1)、
success:function(data){ if(data.message == "IsAjax"){ window.location.href="m-web/user/toLogin" return; } }
(2)改jQuery源码然后在做压缩,是针对全局的方式来修改的(建议)
if ( isSuccess ) {// if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let‘s convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; //解决ajax拦截问题 var result = responses.text; if(result.indexOf("IsAjax")>=0){ window.location.href="m-web/user/toLogin"; return; } } }
以上是关于解决拦截器对ajax请求的的拦截的主要内容,如果未能解决你的问题,请参考以下文章