Ajax请求Session过期简单实现
在AnyReport报表系统中想到使用这种比较简单的验证方法,在web应用系统中大部分用户登录信息存放在Session中,当用户访问页面时服务端会判断是否存在Session、而用户请求服务端常用异步请求方法(Ajax),这时Session过期,将无法使当前页面跳转到登录页面。
具体思路:在当前页面document中加一个ajax请求拦截的ajaxError事件,服务端判断session是否过期,如果过期返回一个错误代码如401,然后ajaxError拦截错误判断是服务端的401错误,则将跳转到登录页面。
服务端判断Session失效
服务端一般是拦截器判断Session是否失效、存在,判断用户请求是否是异步请求,异步请求Session失效 设置401返回码,
resp.sendError(401),如果不是异步则直接跳转到登录页面
public class ActionInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
SessionDesc sd = (SessionDesc) request.getSession().getAttribute(LangContants.SESSION_DESC);
if (sd != null) {
return true;
}
//session 失效处理
String requestType = request.getHeader("X-Requested-With");
boolean isAsync = !StringUtils.isEmpty(requestType);
if(isAsync) {
response.sendError(401);//Session失效返回码,错误Msg是“Unauthorized”
} else {
response.sendRedirect(req.getContextPath() + url);
}
return false;
}
}
AjaxError拦截错误信息
服务端401的代码对应的errorMsg是“Unauthorized”,ajaxError要注册到documnet中,这样对于该页面的ajax请求进行error拦截
$(document).ajaxError(function(e, jqXHR, options, errorMsg){
//no login
if(errorMsg == "Unauthorized") {
location.href = "/page/login.jsp";
}
});