在使用 SpringMVC 是,配置了一個 Session 攔截器,用於攔截用戶是否登陸,可是用戶訪問登陸頁面和註冊頁面時就不須要攔截了,這時就須要用到這個標籤了 <mvc:execlude-mapping />。html
代碼上來先:java
<!-- 配置用於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>
有一點要注意:web
就是上面的【攔截】和【不攔截】,【攔截】的標籤要寫在上面。spring
攔截器的代碼:session
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; } }