SpringMVC拦截器实现:当用户访问网站资源时,监听session是否过期
一、拦截器配置
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/user/login"/> <!-- 不拦截登录请求 -->
<mvc:exclude-mapping path="/user/logout"/> <!-- 不拦截注销请求 -->
<mvc:exclude-mapping path="*.jsp"/>
<mvc:exclude-mapping path="*.html"/>
<mvc:exclude-mapping path="*.js"/>
<mvc:exclude-mapping path="*.css"/>
<bean class="org.huaxin.interceptor.AccessInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
二、拦截器编码
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object obj) throws Exception {
System.out.println("[AccessInterceptor]:preHandle执行");
HttpSession session = request.getSession();
ServletContext application = session.getServletContext();
if(application.getAttribute(session.getId()) == null){ //未登录
PrintWriter out = response.getWriter();
StringBuffer sb = new StringBuffer("<script type=\"text/javascript\" charset=\"UTF-8\">");
sb.append("alert(\"你的账号被挤掉,或者没有登录,或者页面已经过期,请重新登录\")");
sb.append("window.location.href='/user/logout';");
sb.append("</script>");
out.print(sb.toString());
out.close();
return false;
}else{ //已经登录
return true;
}
}
三、总结
1.注意这里使用的拦截器是HandlerInterceptor,你的拦截器需要实现这个接口
2.在你的登录handler里面,要将session保存到application中,方便根据sessionId来判断是否存在session
3.sb.append("window.location.href='/user/logout';"); 这行代码是说,执行注销操作,在你的/user/logout 这个handler里面得把页面解析到登录页,方便重新登录