Ajax请求Session超时的解决办法:拦截器 + 封装jquery的post方法
发布时间:2020-12-15 21:43:33 所属栏目:百科 来源:网络整理
导读:目标 :前端系统,后端系统等,统一处理Session超时和系统错误的问题。 可能需要处理的问题 :Session超时、系统500错误、普通的业务错误、权限不足。 同步请求 : Session超时,登录拦截器,重定向到登录页面。 500等系统错误,SpringMVC自定义ExceptionHan
目标:前端系统,后端系统等,统一处理Session超时和系统错误的问题。
可能需要处理的问题:Session超时、系统500错误、普通的业务错误、权限不足。 同步请求: Session超时,登录拦截器,重定向到登录页面。 500等系统错误,SpringMVC自定义ExceptionHanlder,跳转到系统错误页面,给访客友好的提示。 业务错误和权限不足,与500类似。 相对而言,同步方式,处理起来还是比较容易的。 异步请求: 2种方式 1.后端登录拦截器,发现Session超时,给个标记。 后端系统错误捕捉,给个标记。 比如: if (CommonUtil.isAjaxRequest(request)) { response.setHeader(BERROR,"yes"); CommonUtil.jsonError(response); return null; } 前端 <script> $(function() { $.ajaxSetup({ contentType : "application/json;charset=utf-8",complete : function(XMLHttpRequest,textStatus) { // 通过XMLHttpRequest取得响应头, var blogin = XMLHttpRequest.getResponseHeader("blogin"); if (blogin == "yes") { alert("Session time out2"); window.location = "${frontLoginUrl}"; } var berror = XMLHttpRequest.getResponseHeader("berror"); if (berror == "yes") { alert("Session error2"); } } }); }); </script> 2. 封装jquery的post方法。 function post(url,params,fn) { $.post(url,function(data) { if(data.code==-1){ alert("Session time out"); return; } if(data.code==-5){ alert("System error."); return; } if(data.code ==0){ alert("出了点小问题,"+data.msg); return; } if(data.code == -2){ alert("权限不足,请联系网站管理员."); return; } fn(data); }); } 调用方式: post(base + "/home/bankcard/doadd.json",{ "bank" : bank,"card" : card },function(data) { } 参考资料: http://daichangfu.iteye.com/blog/1705097、某前端王的建议
补充几点
1.后端拦截器加标记。 好处是:前端用ajaxSetup,前端没有干扰到任何已有的代码。比如原来$.post不用修改。 坏处是:后端要改。2.前端统一封装post,正好反过来。 前端需要修改已有的代码。 后端不需要修改。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- (1)cocos2d-x-2.2.4搭建windows开发环境
- ruby – ‘array.each do | block |’包括生成的Haml HTML中
- 零配置 之 12.2 注解实现Bean依赖注入 ——跟我学spring3
- ruby-on-rails – 使用Rails和Devise,我想在注册时发送欢迎
- ORACLE EBS常用表及查询语句(最终整理版)
- postgresql 数据导入导出
- postgresql – Postgres:尝试使用不同的unix用户登录时身份
- 实施地理围栏 – C#
- .net – 无法确定“System.Data.SQLite.SQLiteFactory”类型
- c# – WPF BitmapSource ImageSource