因爲瀏覽器的url是可以讓人任意輸入網址進行訪問的,在一個項目中,我們不可能讓用戶不進行操作就能利用url直接訪問系統,因此這篇文章主要講如何避免這個問題。
首先,解決上述的問題,我們利用攔截器技術就可以解決。
在進行實驗之前,我們首先要知道攔截器與過濾器的區別是什麼?先囉嗦一下
在我們需要對用戶的某個請求進行干預,而這種干預稱爲攔截,是通過攔截器攔截的!
而過濾器是用來過濾網站某些資源的,是不經過用戶請求的。比如說我們的項目都要進行編碼過濾器,因爲我們在項目中用的是中文或者其他除英文外的文字,不進行編碼過濾是會造成亂碼的。而這個過濾是不經用戶操作的,因此稱爲過濾器,而不是攔截器。
(以上感覺說的不盡是全對,意思上類似)
好了,現在開始實驗!
1.在包中添加一個攔截器類LoginInterceptor
(不清楚我項目結構和內容的可以在我這系列上一篇的文章可以看到)
LoginInterceptor類:
這個類重寫org.springframework.web.servlet.HandlerInterceptor的接口方法;
preHandle()方法是在用戶訪問前做什麼,因此我們在用戶不登錄系統進行系統內部操作前進行攔截!
1.我們通過httpServletRequest.getRequestURI();獲取當前的url地址。
2.我們進行攔截的是包含login(大寫Login通過toLowerCase方法變成全部字母爲小寫)的url,如果當前的url跟login有關,則不進行攔截,返回true。
3.在處理登錄的Controller的方法裏,如果用戶登錄成功,我們使用Httpsession添加參數爲“user”並添加值。(這個可以在我這系列上一篇的文章web層的LoginController文件中的login()方法可以看到)
4.回到這個類,如果用戶已經登錄過了,服務器裏有其session值,如果其進行系統內部操作這種情況我們要放行!因此在此類中我們獲取session中的user的值,檢查其是否爲空,如果其存在,則放行!
5.如果用戶沒登錄又直接訪問系統內部路由,則返回false,進行攔截!並重定向到路由/to_login。
package com.myhomes.global;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
String url = httpServletRequest.getRequestURI();
if(url.toLowerCase().indexOf("login")>=0){
return true;
}
HttpSession session = httpServletRequest.getSession();
if(session.getAttribute("user")!=null){
return true;
}
httpServletResponse.sendRedirect("/to_login");
return false;
}
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
xml文件配置攔截器
啓動tomcat並進行操作
這裏是控制器路由,有多個路由方法。
1.先未登錄,在url直接訪問登錄後的self路由成功攔截的話會回到to_login路由(因爲我成功了網頁直接跳轉回登錄界面理由,就沒有放圖)
2.成功登錄後不進行退出系統操作,返回登錄界面後繼續訪問訪問登錄後的self路由,如果成功就完成了攔截!