最近在使用ssm框架搭建一個後臺,需要判斷每個請求都判斷是否登入,未登入跳轉到登入頁面,
使用發現 mvc:exclude-mapping 不攔截,發現,怎麼都無效,依然是進行攔截。查了很多資料,總算解決了。
<mvc:interceptors> <mvc:interceptor> <!-- 需攔截的地址 一級目錄 --> <mvc:mapping path="/*.do" /> <mvc:mapping path="/*.ajax" /> <!-- <mvc:mapping path="/*.html" /> --> <!-- 二級目錄 --> <mvc:mapping path="/*/*.do" /> <mvc:mapping path="/*/*.ajax" /> <!-- <mvc:mapping path="/*/*.html" /> --> <!-- 需排除攔截的地址 --> <!-- <mvc:exclude-mapping path="/manager/login.do"/> --> <!-- <mvc:exclude-mapping path="/myblog/login.do"/> 這種寫法攔截不了--> <mvc:exclude-mapping path="/login.do"/> <mvc:exclude-mapping path="/manager/login.html"/> <bean class="com.sun.common.base.SecurityInterceptor" /> </mvc:interceptor> </mvc:interceptors>
原因是: 如果把專案的路徑一起帶上是攔截不了的。
<mvc:exclude-mapping path="/myblog/login.do"/> 這種寫法攔截不了
要寫成這樣才行:
<mvc:exclude-mapping path="/login.do"/>
攔截器程式碼;
package com.sun.common.base;
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 Administrator
*
*/
public class SecurityInterceptor implements HandlerInterceptor {
private static final String LOGIN_URL = "/manager/login.html";
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2) throws Exception {
// TODO Auto-generated method stub
HttpSession session = req.getSession(true);
// 從session 裡面獲取使用者名稱的資訊
Object obj = session.getAttribute("loginUser");
System.err.println("-----------------------------------------進入攔截器---------------------------");
// 判斷如果沒有取到使用者資訊,就跳轉到登陸頁面,提示使用者進行登陸
if (obj == null || "".equals(obj.toString())) {
resp.sendRedirect(LOGIN_URL);
return false;
}
return true;
}
}