spring mvc攔截器HandlerInterceptor

本文主要介紹springmvc中的攔截器,包括攔截器定義和的配置,然后演示了一個鏈式攔截的測試示例,最后通過一個登錄認證的例子展示了攔截器的應用

攔截定義

定義攔截器,實現HandlerInterceptor接口。接口中提供三個方法。

public class HandlerInterceptor1 implements HandlerInterceptor{ //進入 Handler方法之前執行 //用于身份認證、身份授權 //比如身份認證,如果認證通過表示當前用戶沒有登陸,需要此方法攔截不再向下執行 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //return false表示攔截,不向下執行 //return true表示放行 return false; } //進入Handler方法之后,返回modelAndView之前執行 //應用場景從modelAndView出發:將公用的模型數據(比如菜單導航)在這里傳到視圖,也可以在這里統一指定視圖 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } //執行Handler完成執行此方法 //應用場景:統一異常處理,統一日志處理 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } } 

可以從名稱和參數看出各個接口的順序和作用:

  • public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    • 參數最少,只有三個
    • 進入 Handler方法之前執行
    • 用于身份認證、身份授權。比如身份認證,如果認證通過表示當前用戶沒有登陸,需要此方法攔截不再向下執行
  • public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
    • 多了一個modelAndView參數
    • 進入Handler方法之后,返回modelAndView之前執行
    • 應用場景從modelAndView出發:將公用的模型數據(比如菜單導航)在這里傳到視圖,也可以在這里統一指定視圖
  • public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
    • 多了一個Exception的類型的參數
    • 執行Handler完成執行此方法
    • 應用場景:統一異常處理,統一日志處理

攔截器配置

針對HandlerMapping配置

springmvc攔截器針對HandlerMapping進行攔截設置,如果在某個HandlerMapping中配置攔截,經過該HandlerMapping映射成功的handler最終使用該攔截器。

<beanclass="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"><property name="interceptors"> <list> <ref bean="handlerInterceptor1"/> <ref bean="handlerInterceptor2"/> </list> </property> </bean> <bean id="handlerInterceptor1" class="springmvc.intercapter.HandlerInterceptor1"/> <bean id="handlerInterceptor2" class="springmvc.intercapter.HandlerInterceptor2"/> 

一般不推薦使用。

類似全局的攔截器

springmvc配置類似全局的攔截器,springmvc框架將配置的類似全局的攔截器注入到每個HandlerMapping中。

 <!--攔截器 -->
<mvc:interceptors><!--多個攔截器,順序執行 --><mvc:interceptor><!-- /**表示所有url包括子url路徑 --> <mvc:mapping path="/**"/> <bean class="com.iot.learnssm.firstssm.interceptor.HandlerInterceptor1"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.iot.learnssm.firstssm.interceptor.HandlerInterceptor2"></bean> </mvc:interceptor> </mvc:interceptors> 

攔截測試

測試多個攔截器各個方法執行時機

訪問/items/queryItems.action

  • 1.兩個攔截器都放行
DEBUG [http-apr-8080-exec-1] - DispatcherServlet with name 'springmvc' processing GET request for [/ssm1/items/queryItems.action]
DEBUG [http-apr-8080-exec-1] - Looking up handler method for path /items/queryItems.action
DEBUG [http-apr-8080-exec-1] - Returning handler method [public org.springframework.web.servlet.ModelAndView com.iot.learnssm.firstssm.controller.ItemsController.queryItems(javax.servlet.http.HttpServletRequest,com.iot.learnssm.firstssm.po.ItemsQueryVo) throws java.lang.Exception]
DEBUG [http-apr-8080-exec-1] - Returning cached instance of singleton bean 'itemsController'
DEBUG [http-apr-8080-exec-1] - Last-Modified value for [/ssm1/items/queryItems.action] is: -1
HandlerInterceptor1...preHandle
HandlerInterceptor2...preHandle
DEBUG [http-apr-8080-exec-1] - Fetching JDBC Connection from DataSource
DEBUG [http-apr-8080-exec-1] - Registering transaction synchronization for JDBC Connection
DEBUG [http-apr-8080-exec-1] - Returning JDBC Connection to DataSource
HandlerInterceptor2...postHandle
HandlerInterceptor1...postHandle
DEBUG [http-apr-8080-exec-1] - Rendering view [org.springframework.web.servlet.view.JstlView: name 'items/itemsList'; URL [/WEB-INF/jsp/items/itemsList.jsp]] in DispatcherServlet with name 'springmvc'
DEBUG [http-apr-8080-exec-1] - Added model object 'itemtypes' of type [java.util.HashMap] to request in view with name 'items/itemsList'
DEBUG [http-apr-8080-exec-1] - Added model object 'itemsQueryVo' of type [com.iot.learnssm.firstssm.po.ItemsQueryVo] to request in view with name 'items/itemsList'
DEBUG [http-apr-8080-exec-1] - Added model object 'org.springframework.validation.BindingResult.itemsQueryVo' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'items/itemsList'
DEBUG [http-apr-8080-exec-1] - Added model object 'itemsList' of type [java.util.ArrayList] to request in view with name 'items/itemsList'
DEBUG [http-apr-8080-exec-1] - Forwarding to resource [/WEB-INF/jsp/items/itemsList.jsp] in InternalResourceView 'items/itemsList'
HandlerInterceptor2...afterCompletion
HandlerInterceptor1...afterCompletion
DEBUG [http-apr-8080-exec-1] - Successfully completed request

總結:preHandle方法按順序執行,postHandle和afterCompletion按攔截器配置的逆向順序執行。

2.攔截器1放行,攔截器2不放行

DEBUG [http-apr-8080-exec-8] - DispatcherServlet with name 'springmvc' processing GET request for [/ssm1/items/queryItems.action]
DEBUG [http-apr-8080-exec-8] - Looking up handler method for path /items/queryItems.action
DEBUG [http-apr-8080-exec-8] - Returning handler method [public org.springframework.web.servlet.ModelAndView com.iot.learnssm.firstssm.controller.ItemsController.queryItems(javax.servlet.http.HttpServletRequest,com.iot.learnssm.firstssm.po.ItemsQueryVo) throws java.lang.Exception]
DEBUG [http-apr-8080-exec-8] - Returning cached instance of singleton bean 'itemsController'
DEBUG [http-apr-8080-exec-8] - Last-Modified value for [/ssm1/items/queryItems.action] is: -1
HandlerInterceptor1...preHandle
HandlerInterceptor2...preHandle
HandlerInterceptor1...afterCompletion
DEBUG [http-apr-8080-exec-8] - Successfully completed request

總結:

  • 攔截器1放行,攔截器2 preHandle才會執行。
  • 攔截器2 preHandle不放行,攔截器2 postHandle和afterCompletion不會執行。
  • 只要有一個攔截器不放行,postHandle不會執行。

3.兩個攔截器都不放

DEBUG [http-apr-8080-exec-9] - DispatcherServlet with name 'springmvc' processing GET request for [/ssm1/items/queryItems.action]
DEBUG [http-apr-8080-exec-9] - Looking up handler method for path /items/queryItems.action
DEBUG [http-apr-8080-exec-9] - Returning handler method [public org.springframework.web.servlet.ModelAndView com.iot.learnssm.firstssm.controller.ItemsController.queryItems(javax.servlet.http.HttpServletRequest,com.iot.learnssm.firstssm.po.ItemsQueryVo) throws java.lang.Exception]
DEBUG [http-apr-8080-exec-9] - Returning cached instance of singleton bean 'itemsController'
DEBUG [http-apr-8080-exec-9] - Last-Modified value for [/ssm1/items/queryItems.action] is: -1
HandlerInterceptor1...preHandle
DEBUG [http-apr-8080-exec-9] - Successfully completed request

總結:

  • 攔截器1 preHandle不放行,postHandle和afterCompletion不會執行。
  • 攔截器1 preHandle不放行,攔截器2不執行。

4.攔截器1不放行,攔截器2放行

DEBUG [http-apr-8080-exec-8] - DispatcherServlet with name 'springmvc' processing GET request for [/ssm1/items/queryItems.action]
DEBUG [http-apr-8080-exec-8] - Looking up handler method for path /items/queryItems.action
DEBUG [http-apr-8080-exec-8] - Returning handler method [public org.springframework.web.servlet.ModelAndView com.iot.learnssm.firstssm.controller.ItemsController.queryItems(javax.servlet.http.HttpServletRequest,com.iot.learnssm.firstssm.po.ItemsQueryVo) throws java.lang.Exception]
DEBUG [http-apr-8080-exec-8] - Returning cached instance of singleton bean 'itemsController'
DEBUG [http-apr-8080-exec-8] - Last-Modified value for [/ssm1/items/queryItems.action] is: -1
HandlerInterceptor1...preHandle
DEBUG [http-apr-8080-exec-8] - Successfully completed request

和兩個攔截器都不行的結果一致,因為攔截器1先執行,沒放行

  • 小結

根據測試結果,對攔截器應用。

比如:統一日志處理攔截器,需要該攔截器preHandle一定要放行,且將它放在攔截器鏈接中第一個位置。

比如:登陸認證攔截器,放在攔截器鏈接中第一個位置。權限校驗攔截器,放在登陸認證攔截器之后。(因為登陸通過后才校驗權限,當然登錄認證攔截器要放在統一日志處理攔截器后面)

攔截器應用(實現登陸認證)

需求

  • 1.用戶請求url
  • 2.攔截器進行攔截校驗
    • 如果請求的url是公開地址(無需登陸即可訪問的url),讓放行
    • 如果用戶session 不存在跳轉到登陸頁面
    • 如果用戶session存在放行,繼續操作。

登陸controller方法

@Controller
public class LoginController { // 登陸 @RequestMapping("/login") public String login(HttpSession session, String username, String password) throws Exception { // 調用service進行用戶身份驗證 // ... // 在session中保存用戶身份信息 session.setAttribute("username", username); // 重定向到商品列表頁面 return "redirect:/items/queryItems.action"; } // 退出 @RequestMapping("/logout") public String logout(HttpSession session) throws Exception { // 清除session session.invalidate(); // 重定向到商品列表頁面 return "redirect:/items/queryItems.action"; } } 

登陸認證攔截實現

  • 代碼實現
/*** Created by brian on 2016/3/8.* 登陸認證攔截器*/public class LoginInterceptor implements HandlerInterceptor { //進入 Handler方法之前執行 //用于身份認證、身份授權 //比如身份認證,如果認證通過表示當前用戶沒有登陸,需要此方法攔截不再向下執行 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //獲取請求的url String url = request.getRequestURI(); //判斷url是否是公開 地址(實際使用時將公開 地址配置配置文件中) //這里公開地址是登陸提交的地址 if(url.indexOf("login.action")>=0){ //如果進行登陸提交,放行 return true; } //判斷session HttpSession session = request.getSession(); //從session中取出用戶身份信息 String username = (String) session.getAttribute("username"); if(username != null){ //身份存在,放行 return true; } //執行這里表示用戶身份需要認證,跳轉登陸頁面 request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); //return false表示攔截,不向下執行 //return true表示放行 return false; } //進入Handler方法之后,返回modelAndView之前執行 //應用場景從modelAndView出發:將公用的模型數據(比如菜單導航)在這里傳到視圖,也可以在這里統一指定視圖 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("LoginInterceptor...postHandle"); } //執行Handler完成執行此方法 //應用場景:統一異常處理,統一日志處理 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("LoginInterceptor...afterCompletion"); } } 
  • 攔截器配置
<!--攔截器 -->
<mvc:interceptors><!--多個攔截器,順序執行 --><!-- 登陸認證攔截器 --><mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.iot.learnssm.firstssm.interceptor.LoginInterceptor"></bean> </mvc:interceptor> ...省略 

轉載于:https://www.cnblogs.com/thinkingandworkinghard/p/8124295.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/252597.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/252597.shtml
英文地址,請注明出處:http://en.pswp.cn/news/252597.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

mysql show 語句大全

mysql show 語句大全 show open tables; 基于本人對MySQL的使用&#xff0c;現將常用的MySQL show 語句列舉如下&#xff1a; 1.show databases ; // 顯示mysql中所有數據庫的名稱 2.show tables [from database_name]; // 顯示當前數據庫中所有表的名稱 3.show columns from …

阿里云Aliplayer高級功能介紹(一):視頻截圖

基本介紹H5 Video是不提供截圖的API的&#xff0c; 視頻截圖需要借助Canvas&#xff0c;通過Canvas提供的drawImage方法&#xff0c;把Video的當前畫面渲染到畫布上&#xff0c; 最終通過toDataURL方法可以導出圖片的base64編碼&#xff0c;基本就完成了圖片截圖的功能。 功能實…

POJ 1151 Atlantis 線段樹+掃描線

解題思路: 先將y軸進行離散化。n個矩形的2n個橫邊縱坐標共構成最多2n-1個區間的邊界&#xff0c;對這些區間編號&#xff0c;建立起線段樹。 x軸記錄左邊和右邊&#xff0c;左邊時是矩形面積增加&#xff0c;覆蓋層數增加邊&#xff0c;右邊是形面積減少&#xff0c;覆蓋層數減…

分頁

1.首先在數據庫中建立一個視圖&#xff08;在aspx中sql查詢語句是view_student不是student&#xff09;&#xff0c;在視圖里創建create view view_student--創建視圖as row_number 行號 一條數據是一行 分頁功能要根據行數運算select *,row_number() over(order by stuNo desc…

NFS服務端的安裝

執行以下四步操作即可完成在虛擬機上安裝完成NFS的服務端&#xff1a;第一步&#xff1a;在虛擬機上安裝nfs服務&#xff1a; sudo apt install nfs-kernel-server 第二步&#xff1a;修改文件 sudo vi /etc/exports 在文件末尾增加 /home/zzf/hisi-sdk 192.16…

【C++STL/紅黑樹】POJ 3481 DoubleQueue

POJ 3481 Double Queue 描述&#xff1a; 新成立的BIG-Bank在不切雷斯特開了一間新辦公室,使用了由IBM羅馬尼亞的現代計算機辦公環境,運用了現代信息技術.一般來說,銀行的每個顧客都有一個識別碼K,并且每一個來銀行的顧客都會被給予一個優先級P.銀行主管的一個大膽想法震驚了公…

基礎表單筆記

表單數據要向服務端提交的話 每個表單都要指定一些屬性就是name""和value"" value就是用戶寫什么就是什么 來提交name就是對這個表單進行一個標識 <from> 輸入用戶名<input type"text" name"user" value""/>這…

PCIE總線-PCI、PCIE關系及信號定義

PCI(Peripheral Component Interconnect)總線規范在上世紀九十年代由Intel提出。在處理器體系結構中&#xff0c;PCI總線屬于局部總線(Local Bus)。局部總線作為系統總線的延伸&#xff0c;主要功能是為了連接外部設備。 處理器主頻的不斷提升&#xff0c;要求速度更快&#x…

SQL Server:SQL Like 通配符特殊用法:Escape

%&#xff1a;匹配零個及多個任意字符&#xff1b; _&#xff1a;與任意單字符匹配&#xff1b; []&#xff1a;匹配一個范圍&#xff1b; [^]&#xff1a;排除一個范圍 &#xff1b;-&#xff1a;連字符 Symbol Meaning like 5[%] 5% like [_]n _n like [a-cdf] a, b, c, d, o…

案例篇-HBase RowKey 設計指南

1.為什么 Rowkey 這么重要 1.1 RowKey 到底是什么 我們常說看一張 HBase 表設計的好不好&#xff0c;就看它的 RowKey 設計的好不好。可見 RowKey 在 HBase 中的地位。那么 RowKey 到底是什么?RowKey 的特點 如下: 類似于 MySQL、Oracle 中的主鍵&#xff0c;用于標示唯一的行…

PCIe簡介及引腳定義

隨著現代處理器技術的發展&#xff0c;在互連領域中&#xff0c;使用高速差分總線替代并行總線是大勢所趨。與單端并行信號相比&#xff0c;高速差分信號可以使用更高的時鐘頻率&#xff0c;從而使用更少的信號線&#xff0c;完成之前需要許多單端并行數據信號才能達到的總線帶…

IDEA下搜狗輸入法輸入中文時卡著不動的參考解決方法

【問題描述】 在IntelliJ IDEA工具的java編輯窗口&#xff0c;給代碼增加注釋時發現&#xff0c;輸入中文時&#xff0c;搜狗輸入法界面不動&#xff0c;只顯示第一個字母。如圖&#xff1a; 我想輸入“根據”兩個字&#xff0c;但搜狗輸入法界面一直卡著不刷新&#xff0c;導…

6U VPX板卡資料:6U VPX 高性能計算存儲板卡

6U VPX板卡資料&#xff1a;6U VPX 高性能計算存儲板卡_hexiaoyan827的博客-CSDN博客_vpx板卡

Android: Custom View和include標簽的區別

Custom View&#xff0c; 使用的時候是這樣的&#xff1a; <com.example.home.alltest.view.MyCustomViewandroid:id"id/customView"android:layout_width"match_parent"android:layout_height"wrap_content"></com.example.home.allte…

七 web爬蟲講解2—urllib庫爬蟲—狀態嗎—異常處理—瀏覽器偽裝技術、設置用戶代理...

如果爬蟲沒有異常處理&#xff0c;那么爬行中一旦出現錯誤&#xff0c;程序將崩潰停止工作&#xff0c;有異常處理即使出現錯誤也能繼續執行下去 1.常見狀態嗎 301&#xff1a;重定向到新的URL&#xff0c;永久性302&#xff1a;重定向到臨時URL&#xff0c;非永久性304&#x…

DVI和HDMI中的TMDS接口協議

TMDS&#xff08;Transition Minimized Differential signal&#xff09;&#xff0c;即過渡調制差分信號&#xff0c;也被稱為最小化傳輸差分信號&#xff0c;是指通過異或及異或非等邏輯算法將原始信號數據轉換成10位&#xff0c;前8為數據由原始信號經運算后獲得&#xff0c…

君子眼中皆好人

從前有個國王&#xff0c;在晚年時思量 著&#xff1a;“我有兩個兒子&#xff0c;我應該把王位傳給哪個兒子來統治這個國家呢&#xff1f;”國王決定考驗一下他的兩位王子&#xff0c;哪位最是忠義仁厚&#xff0c;愛護老百姓的明君。國王叫來長子&#xff0c; 對他說&#xf…

GS使用HTTPS登錄的設置過程

1. Windows 增加角色服務 服務器配置管理器&#xff0c; 添加角色服務 增加角色功能里面有&#xff1a; 證書頒發機構 證書頒發機構 web注冊 2. AD CS配置 主要是next操作 獨立ca 根證書 等 3. inetmgr申請證書 在機器名的一層及上面申請證書 保存證書信息 用來使用CA機構進行簽…

TMDS的信號通道

1 TMDS的信號通道&#xff1a; 1個HDMI包括3個TMDS數據通道和1個TMDS時鐘通道。 . 每一個TMDS時鐘周期內&#xff0c;TMDS數據通道上會發送一個10位的字符信息&#xff1b; . 每個TMDS時鐘周期內&#xff0c;編碼器將2位的控制數據、4位的報數據或者8位的視頻數據采取不同 …