SpringMVC 之 mvc:exclude-mapping 不攔截某個請求


在使用 SpringMVC 是,配置了一個 Session 攔截器,用於攔截用戶是否登錄,但是用戶訪問登錄頁面和注冊頁面時就不需要攔截了,這時就需要用到這個標簽了 <mvc:execlude-mapping />。

代碼上來先:

<!-- 配置用於session驗證的攔截器 -->
    <!-- 
        如果有多個攔截器滿足攔截處理的要求,則依據配置的先后順序來執行
     -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 攔截所有的請求,這個必須寫在前面,也就是寫在【不攔截】的上面 -->
            <mvc:mapping path="/**" />
            <!-- 但是排除下面這些,也就是不攔截請求 -->
            <mvc:exclude-mapping path="/login.html" />
            <mvc:exclude-mapping path="/account/login.do" />
            <mvc:exclude-mapping path="/account/regist.do" />
            <bean class="com.msym.cloudnote.interceptors.SessionInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

 

有一點要注意:

就是上面的【攔截】和【不攔截】,【攔截】的標簽要寫在上面。

攔截器的代碼:

package com.msym.cloudnote.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 判斷是否登錄的攔截器
 * @author 碼上猿夢
 *  http://www.cnblogs.com/daimajun/
 */
public class SessionInterceptor  implements HandlerInterceptor {

    
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        
    }

    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handel) throws Exception {
        HttpSession session = req.getSession();
        // 從session當中獲取特定的數據
        Object obj = session.getAttribute("name");
        if (obj == null) {
            // 未登錄,重定向到登錄頁面
            res.sendRedirect(req.getContextPath()+"/login.html");
            return false;
        }
        // 已登錄,繼續向后調用
        return true;
    }
}


免責聲明!

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



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