本文主要向大家介绍了SpringMVC拦截器实现:当用户访问网站资源时,监听session是否过期的代码,具体如下:
一、拦截器配置
1
2
3
4
5
6
7
8
9
10
11
12
|
< 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 >
|
二、拦截器编码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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里面得把页面解析到登录页,方便重新登录
以上就是本文关于SpringMVC拦截器实现监听session是否过期详解的全部内容,希望对大家有所帮助,如有不足之处,欢迎留言指出。小编会及时进行更改,感谢朋友们对本站的支持!
原文链接:http://www.cnblogs.com/javafucker/p/7726202.html