SpringMVC攔截器實(shí)現(xiàn)監(jiān)聽session是否過(guò)期詳解
本文主要向大家介紹了SpringMVC攔截器實(shí)現(xiàn):當(dāng)用戶訪問(wèn)網(wǎng)站資源時(shí),監(jiān)聽session是否過(guò)期的代碼,具體如下:
一、攔截器配置
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:exclude-mapping path="/user/login"/> <!-- 不攔截登錄請(qǐng)求 --> <mvc:exclude-mapping path="/user/logout"/> <!-- 不攔截注銷請(qǐng)求 --> <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執(zhí)行"); 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(\"你的賬號(hào)被擠掉,或者沒(méi)有登錄,或者頁(yè)面已經(jīng)過(guò)期,請(qǐng)重新登錄\")"); sb.append("window.location.href='/user/logout';"); sb.append("</script>"); out.print(sb.toString()); out.close(); return false; }else{ //已經(jīng)登錄 return true; } }
三、總結(jié)
1.注意這里使用的攔截器是HandlerInterceptor,你的攔截器需要實(shí)現(xiàn)這個(gè)接口
2.在你的登錄handler里面,要將session保存到application中,方便根據(jù)sessionId來(lái)判斷是否存在session
3.sb.append("window.location.href='/user/logout';"); 這行代碼是說(shuō),執(zhí)行注銷操作,在你的/user/logout 這個(gè)handler里面得把頁(yè)面解析到登錄頁(yè),方便重新登錄
以上就是本文關(guān)于SpringMVC攔截器實(shí)現(xiàn)監(jiān)聽session是否過(guò)期詳解的全部?jī)?nèi)容,希望對(duì)大家有所幫助,感興趣的朋友可以繼續(xù)參閱本站:Java監(jiān)聽器的作用及用法代碼示例、SpringMVC開發(fā)restful API之用戶查詢代碼詳解、springmvc接收jquery提交的數(shù)組數(shù)據(jù)代碼分享等,如有不足之處,歡迎留言指出。小編會(huì)及時(shí)進(jìn)行更改,感謝朋友們對(duì)本站的支持!
相關(guān)文章
Java中Optional.of()方法及源碼解析(非常詳細(xì)!)
這篇文章主要給大家介紹了關(guān)于Java中Optional.of()方法及源碼解析的相關(guān)資料,Java中java.util .Optional類的of()方法用于獲得該Optional類中具有指定類型的指定值的一個(gè)實(shí)例,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-06-06POI通過(guò)模板導(dǎo)出EXCEL文件的實(shí)例
下面小編就為大家?guī)?lái)一篇POI通過(guò)模板導(dǎo)出EXCEL文件的實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08三分鐘帶你了解SpringBoot真正的啟動(dòng)引導(dǎo)類
這篇文章主要介紹了三分鐘帶你了解SpringBoot真正的啟動(dòng)引導(dǎo)類,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11EventBus與Spring Event區(qū)別詳解(EventBus 事件機(jī)制,Spring Event事件機(jī)制)
這篇文章主要介紹了EventBus與Spring Event區(qū)別,需要的朋友可以參考下2020-02-02