小弟第一次发帖,最近为了解决这个问题查了很久,终于解决了,不一定很好,各位看看吧。
因为ajax无法执行拦截器的跳转主页响应,所以跳转只能写在前台,但是为了不改动已经写好的代码,只能进行统一设置,而ajaxSetup的统一设置只是缺省设置,不太好用,因此使用ajax重写是最好的解决办法。
jQuery(function($){
// 备份jquery的ajax方法
var _ajax=$.ajax;
// 重写ajax方法,先判断登录在执行error函数
$.ajax=function(opt){
var _error = opt && opt.error || function(a, b){};
var _opt = $.extend(opt, {
error:function(data, textStatus){
if(data.status==401){
alert("登录超时,请重新登录!");
storage.clear();//清空sessionStorage(类似cookie的东西)
window.location.replace("/index.html");
}else{
_error(data, textStatus);
}
}
});
_ajax(_opt);
};
});
如上代码,当拦截器返回false时,会执行ajax的error回调函数,因此重写的error是先判断error是不是因为session失效,是的话就跳转,不是的话再执行error函数。
顺便把拦截器贴上来吧,不知道能不能帮到大家
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private LoginService loginService;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println(">>>LoginInterceptor>>>>>>>登录校验拦截器开始执行>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
//获取请求的URL
String url = request.getRequestURI();
System.out.println("------------------------------url:"+url+"------------------------------");
//设置例外url
if(url.indexOf("login")>=0 || url.indexOf("menu")>=0 || url.indexOf("error")>=0){
return true;
}
//获取Session
HttpSession session = request.getSession();
Long uid = (Long)session.getAttribute("uid");
String guid = (String)session.getAttribute("guid");
// System.out.println("uid:"+uid+"\nguid:"+guid);
if (loginService == null) {//解决service为null无法注入问题
System.out.println("loginService is null!!! don't worry,we will fixed it");
BeanFactory factory = WebApplicationContextUtils
.getRequiredWebApplicationContext(request
.getServletContext());
loginService = (LoginService) factory.getBean("loginService");
}
try {
if (uid != null) {
List guidList = loginService.findGuidByUid(uid);
if (guid.equals(guidList.get(0).toString())) {
return true;
}else{//随机验证码匹配失败的
/**暂无特殊处理*/
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
//session中没有信息的,跳转到主页
if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
response.setStatus(401);
}else{
request.getRequestDispatcher("/index.html").forward(request, response);
}
return false;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// System.out.println(">>>LoginInterceptor>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
//System.out.println(">>>LoginInterceptor>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
}
}