解决拦截器对ajax请求的拦截实例详解
程序员文章站
2022-10-19 11:26:40
解决拦截器对ajax请求的的拦截
拦截器配置:
public boolean prehandle(httpservletrequest request, h...
解决拦截器对ajax请求的的拦截
拦截器配置:
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、判断 string xrequested =request.getheader("x-requested-with") 的值,目的是判断是否是ajax请求。
2、response.getwriter().write("isajax");写出一个响应的数据给ajax,这样就可以在ajax里面做判断
判断的方式存在两种方式:
1)直接在ajax里面做判断(不建议)
success:function(data){ if(data == "isajax"){ window.location.href="m-web/user/tologin" return; } }
2)改ajax源码然后在做压缩,是针对全局的方式来修改的(建议)
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; } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!