SpringMVC攔截器實現:當用戶訪問網站資源時,監聽session是否過期


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里面得把頁面解析到登錄頁,方便重新登錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM