本文主要向大家介紹了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