struts2中拦截AJAX请求,判断SESSION为空跳转到登录页面
参考
http://endual.iteye.com/blog/1620368
首先介绍情况:我们项目用STRUTS2+jquery easyui形式,发现在登录超时后,easyui的datagrid总显示为空(其实后台数据库是有数据的),但是又没有任何提示(我知道可以用类似 暂无数据 这样的方法来处理,但是实际上后台是有数据的,这样提示是不合理不真实的),我想要的是发现登录超时后,直接提示登录超时,然后跳转到登录页面。
方法有二: 方法一:在每个ACTION中进行判断处理,然后页面前台接收,并进行跳转到登录页面处理,缺点:每个类和前台每个页面都要写代码,麻烦
后台action处理:
BtUser user=getSessionUser("loginUser");
if(null==user){
String errStr="{\"msgtitle\":\"登录超时\",\"msgtype\":\"error\",\"msginfo\":\"登录超时请重新登录!\",\"msgsta\":2,\"total\":0,\"rows\":[]}";
System.out.println(errStr);
printJsonStr(errStr);
}else{
正常业务处理
} 然后在前台页面上,在datagrid的onLoadSuccess事件中进行处理,片断如下
onLoadSuccess:function(data){
var result = eval(data);
if(result.total==0 && result.msgType=="error"){
$.messager.alert(result.msgTitle,result.msgInfo,result.msgType);
top.location.href="user_login.jsp";
}
}, 方法二:利用struts2的拦截器进行处理,
public class LoginCheckInterceptor extends MethodFilterInterceptor { /**
* 是否为AJAX请求
*/
public boolean isAjaxRequest(HttpServletRequest request) {
String header = request.getHeader("X-Requested-With");
if (header != null && "XMLHttpRequest".equals(header))
return true;
else
return false;
}
protected String doIntercept(ActionInvocation ai) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse(); bean= (BtUser)ServletActionContext.getRequest().getSession().getAttribute("loginUser");
//验证是否已经登录
if (null==bean){//尚未登录,跳转至登录页面
if(isAjaxRequest(request)){
response.sendError(408);//request timeout
return "tologin";
}else{
return "tologin";
} }else{
return ai.invoke();
}
}
} 然后前台怎么处理呢,利用AJAX的全局事件,因为我把所有的常用JS,CSS都放在inc_right.jsp中了,所以为了省事我还放在这里面
<%
String bp = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<script>
var glb_bp='<%=bp%>';
</script>
<script src="<%=currPath %>/jslib/global_session.js"></script> global_session.js
//从jQuery1.8开始,.ajaxError()方法应该只被附加到document上
$(document).ajaxError(function(event,jqxhr,settings,exception){
if(jqxhr.status==408){
alert("操作超时,请重新登录!");
top.location =glb_bp+ "user_login.jsp";
}
});
完美了,原来做好的页面不用做任何修改就可以。当然如果你的页面比较少,也可以将上面的代码直接放在
$(function(){
//从jQuery1.8开始,.ajaxError()方法应该只被附加到document上
$(document).ajaxError(function(event,jqxhr,settings,exception){
if(jqxhr.status){
alert("操作超时,请重新登录!");
alert(glb_bp);
top.location =glb_bp+ "user_login.jsp";
}else if(jqxhr.status==403){
alert("没有权限!");
window.location = "common/nopermit.html";
}else if(jqxhr.status==500){
alert("发生错误!");
window.location = "common/error.html";
}
}
struts2中拦截AJAX请求,判断SESSION为空跳转到登录页面
猜你喜欢
转载自xmllong.iteye.com/blog/2162922
今日推荐
周排行