您的位置:首页 > 编程语言 > Java开发

SpringMVC 拦截器遇到浏览器请求/favicon.ico被拦截导致触发session失效问题的处理办法

2017-12-18 13:11 716 查看
现状做的一个练手项目,根据慕课网的仿大众点评源码自己修改的,使用session拦截器+auth拦截器。

之前用的Chrome浏览器,遇到的问题:登录后台,加载完菜单后,点进每一个子菜单都被踢回到login,打断点总是发现session被莫名其妙的清掉,期初以为是session拦截器出了问题,但源码基本没动呀,该不会有坑?

/**
* session拦截器
*/
public class SessionInterceptor implements HandlerInterceptor {

/**
* 在进入Handler方法执行之前执行本方法
*
* @return true:执行下一个拦截器,直到所有拦截器都执行完,再执行被拦截的Controller
* false:从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//这里的用户信息在加载完菜单后就变成了null
System.out.println(request.getSession().getAttribute(SessionKeyConst.USER_INFO));
if (request.getSession().getAttribute(SessionKeyConst.USER_INFO) != null) {
return true;
}
// 针对ajax请求处理
if (request.getHeader("x-requested-with") != null) {
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
response.setHeader("url", basePath + "/login/sessionTimeout");
} else {
request.getRequestDispatcher("/login/sessionTimeout").forward(request, response);
}
return false;
}
}

后来观察AuthInterceptor的uri,发现下面代码的情况(/login/sessionTimeout和下面的/login/noAuth方法都是触发的session.invalidate())

public class AuthInterceptor implements HandlerInterceptor {

/**
* 在进入Handler方法执行之前执行本方法
*
* @return true:执行下一个拦截器,直到所有拦截器都执行完,再执行被拦截的Controller
* false:从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//这里的request.getServletPath()出现了/favicon.ico的请求
if (CommonUtil.contains(request.getSession(), request.getServletPath(), request.getMethod())) {
return true;
}
// 针对ajax请求处理
if (request.getHeader("x-requested-with") != null) {
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
response.setHeader("url", basePath + "/login/noAuth");
} else {
request.getRequestDispatcher("/login/noAuth").forward(request, response);
}
return false;
}
}
这个/favicon.ico请求从哪来的?我搜了整个项目都没找到favicon.ico的字眼,我的项目里也没有favicon.ico这个文件,后来通过Google,发现浏览器自己会在页面加载完成后发起一个/favicon.ico的请求,这就有点蛋疼了,你请求都不告诉我一声,结果被我的auth拦截器拦下造成我session莫名其妙的被清空,害的我还找了半天原因。

解决办法:拦截器直接放行就ok啦~

<!-- 过滤浏览器发起的/favicon.ico请求,防止session被清空 -->
<mvc:exclude-mapping path="/favicon.ico"/>
再从需要的页面里引用上icon
<link rel="shortcut icon" href="/favicon.ico"/>
<link rel="bookmark" href="/favicon.ico"/>


就ok了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐