This article mainly introduces detailed information about how the interceptor can intercept ajax requests. For more information, see intercept ajax requests by the interceptor.
Interceptor Configuration:
Public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {// obtain the String token = (String) request to determine whether the logged-in session exists. 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. judge the value of String XRequested = request. getHeader ("X-Requested-With") to determine whether it is an ajax request.
2. response. getWriter (). write ("IsAjax"); write a response data to ajax, so that you can make judgments in ajax.
There are two methods to determine:
1) directly make judgment in ajax (not recommended)
success:function(data){ if(data == "IsAjax"){ window.location.href="m-web/user/toLogin" return; }}
2) modify the ajax source code and then compress it in a global manner (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; // solve the ajax interception problem var result = responses. text; if (result. indexOf ("IsAjax")> = 0) {window. location. href = "m-web/user/toLogin"; return ;}}}
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!
For more details about how the interceptor intercepts ajax requests, refer to the PHP Chinese website!
Related Articles:
Block global ajax request instance parsing through JS
How to Use Mock. js to intercept AJAX requests in the Node. js server environment
Use php to check for ajax request methods