Home > Article > Web Front-end > Detailed explanation of interception examples of interceptors on ajax requests
Solve the interception of ajax requests by the interceptor
Interceptor configuration:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object obj) throws Exception { //获取判定登陆的session是否存在 String token = (String) request.getSession().getAttribute("token"); String postId = (String) request.getSession().getAttribute("postId"); if(token == null || token == ""){ String XRequested =request.getHeader("X-Requested-With"); if("XMLHttpRequest".equals(XRequested)){ response.getWriter().write("IsAjax"); }else{ response.sendRedirect("/m-web/user/toLogin"); } return false; } if(postId == null || postId == ""){ String XRequested =request.getHeader("X-Requested-With"); if("XMLHttpRequest".equals(XRequested)){ response.getWriter().write("IsAjax"); }else{ response.sendRedirect("/m-web/user/toLogin"); } return false; } return true; }
1. Determine String XRequested =request.getHeader("X-Requested-With") The value is to determine whether it is an ajax request.
2. response.getWriter().write("IsAjax"); Write a response data to ajax, so that you can make a judgment in ajax.
There are two ways to judge. Method:
1) Make judgment directly in ajax (not recommended)
success:function(data){ if(data == "IsAjax"){ window.location.href="m-web/user/toLogin" return; } }
2) Change the ajax source code and then perform compression, which is modified in a global way (recommended)
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; } } }
Thank you for reading, I hope it can help everyone, thank you for your support of this site!
For more detailed examples of interception of ajax requests by interceptors, please pay attention to the PHP Chinese website for related articles!
Related articles:
Interception of global ajax request instance analysis through JS
Use Mock.js to intercept AJAX in Node.js server environment Requested tutorial