自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一篇學(xué)會攔截器的騷操作

開發(fā) 架構(gòu)
“Spring MVC中的攔截器(Interceptor)類似于Servlet中的過濾器(Filter),它主要用于攔截用戶請求并作相應(yīng)的處理。例如通過攔截器可以進(jìn)行權(quán)限驗(yàn)證、記錄請求信息的日志、判斷用戶是否登錄等。

[[433065]]

文末本文轉(zhuǎn)載自微信公眾號「程序員千羽 」,作者程序員千羽。轉(zhuǎn)載本文請聯(lián)系程序員千羽公眾號。

GitHub:https://github.com/nateshao/ssm/tree/master/110-springmvc-intercepter

什么是攔截器?

Spring MVC中的攔截器(Interceptor)類似于Servlet中的過濾器(Filter),它主要用于攔截用戶請求并作相應(yīng)的處理。例如通過攔截器可以進(jìn)行權(quán)限驗(yàn)證、記錄請求信息的日志、判斷用戶是否登錄等。

要使用Spring MVC中的攔截器,就需要對攔截器類進(jìn)行定義和配置。通常攔截器類可以通過兩種方式來定義。

  • 第一種:通過實(shí)現(xiàn)HandlerInterceptor接口,或繼承HandlerInterceptor接口的實(shí)現(xiàn)類(如HandlerInterceptorAdapter)來定義。
  • 第二種:通過實(shí)現(xiàn)WebRequestInterceptor接口,或繼承WebRequestInterceptor接口的實(shí)現(xiàn)類來定義。

以實(shí)現(xiàn)HandlerInterceptor接口方式為例,自定義攔截器類的代碼如下:

  1. public class CustomInterceptor implements HandlerInterceptor { 
  2.     /** 
  3.      * 該方法會在控制器方法前執(zhí)行,其返回值表示是否中斷后續(xù)操作。 
  4.      * 當(dāng)其返回值為true時,表示繼續(xù)向下執(zhí)行; 
  5.      * 當(dāng)其返回值為false時,會中斷后續(xù)的所有操作。 
  6.      * @param request 
  7.      * @param response 
  8.      * @param handler 
  9.      * @return 
  10.      * @throws Exception 
  11.      */ 
  12.     @Override 
  13.     public boolean preHandle(HttpServletRequest request, 
  14.                              HttpServletResponse response, Object handler) throws Exception { 
  15.         System.out.println("CustomInterceptor...preHandle"); 
  16.         //對攔截的請求進(jìn)行放行處理 
  17.         return true
  18.     } 
  19.  
  20.     /** 
  21.      * 該方法會在控制器方法調(diào)用之后,且解析視圖之前執(zhí)行。 
  22.      * 可以通過此方法對請求域中的模型和視圖做出進(jìn)一步的修改。 
  23.      * @param request 
  24.      * @param response 
  25.      * @param handler 
  26.      * @param modelAndView 
  27.      * @throws Exception 
  28.      */ 
  29.     @Override 
  30.     public void postHandle(HttpServletRequest request, 
  31.                            HttpServletResponse response, Object handler, 
  32.                            ModelAndView modelAndView) throws Exception { 
  33.         System.out.println("CustomInterceptor...postHandle"); 
  34.     } 
  35.  
  36.     /** 
  37.      * 該方法會在整個請求完成,即視圖渲染結(jié)束之后執(zhí)行。 
  38.      * 可以通過此方法實(shí)現(xiàn)一些資源清理、記錄日志信息等工作。 
  39.      * @param request 
  40.      * @param response 
  41.      * @param handler 
  42.      * @param ex 
  43.      * @throws Exception 
  44.      */ 
  45.     @Override 
  46.     public void afterCompletion(HttpServletRequest request, 
  47.                                 HttpServletResponse response, Object handler, 
  48.                                 Exception ex) throws Exception { 
  49.         System.out.println("CustomInterceptor...afterCompletion"); 
  50.     } 

要使自定義的攔截器類生效,還需要在Spring MVC的配置文件中進(jìn)行配置。

  1. <mvc:interceptors> 
  2.         <!--    全局?jǐn)r截器,攔截所有請求    --> 
  3.         <bean class="com.nateshao.interceptor.CustomInterceptor"/>// 
  4.  
  5.         <mvc:interceptor> 
  6.         <!--   **配置,表示攔截所有路徑  --> 
  7.             <mvc:mapping path="/**"/> 
  8.         <!--   配置不需要攔截的路徑     --> 
  9.             <mvc:exclude-mapping path=""/> 
  10.  
  11.             <bean class="com.nateshao.interceptor.Interceptor1"/> 
  12.         </mvc:interceptor> 
  13.         <mvc:interceptor> 
  14.             <!--  /hello表示攔截所有以“/hello”結(jié)尾的路徑   --> 
  15.             <mvc:mapping path="/hello"/> 
  16.             
  17.             <bean class="com.nateshao.interceptor.Interceptor2"/> 
  18.         </mvc:interceptor> 
  19.         ... 
  20.     </mvc:interceptors> 

注意:< mvc:interceptor >中的子元素必須按照上述代碼的配置順序進(jìn)行編寫,否則文件會報(bào)錯。

2. 攔截器的執(zhí)行流程

在運(yùn)行程序時,攔截器的執(zhí)行是有一定順序的,該順序與配置文件中所定義的攔截器的順序相關(guān)。

單個攔截器,在程序中的執(zhí)行流程如下圖所示:

多個攔截器的執(zhí)行流程

“多個攔截器(假設(shè)有兩個攔截器Interceptor1和Interceptor2,并且在配置文件中, Interceptor1攔截器配置在前),在程序中的執(zhí)行流程如下圖所示:

3. 應(yīng)用案例

案例說明 : 實(shí)現(xiàn)用戶登錄權(quán)限驗(yàn)證

“案例中,只有登錄后的用戶才能訪問系統(tǒng)中的主頁面,如果沒有登錄系統(tǒng)而直接訪問主頁面,則攔截器會將請求攔截,并轉(zhuǎn)發(fā)到登錄頁面,同時在登錄頁面中給出提示信息。如果用戶名或密碼錯誤,也會在登錄頁面給出相應(yīng)的提示信息。當(dāng)已登錄的用戶在系統(tǒng)主頁中單擊“退出”鏈接時,系統(tǒng)同樣會回到登錄頁面。

login.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8" 
  2.      pageEncoding="UTF-8"%> 
  3. <html> 
  4. <head> 
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
  6. <title>系統(tǒng)主頁</title> 
  7. </head> 
  8. <body> 
  9.     當(dāng)前用戶:${USER_SESSION.username}   
  10.     <a href="${pageContext.request.contextPath }/logout">退出</a>   
  11. </body> 
  12. </html> 

LoginInterceptor.java

  1. package com.nateshao.interceptor; 
  2.  
  3. import com.nateshao.po.User
  4. import org.springframework.web.servlet.HandlerInterceptor; 
  5. import org.springframework.web.servlet.ModelAndView; 
  6. import javax.servlet.http.HttpServletRequest; 
  7. import javax.servlet.http.HttpServletResponse; 
  8. import javax.servlet.http.HttpSession; 
  9.  
  10. /** 
  11.  * @date Created by 邵桐杰 on 2021/10/22 12:50 
  12.  * @微信公眾號 程序員千羽 
  13.  * @個人網(wǎng)站 www.nateshao.cn 
  14.  * @博客 https://nateshao.gitee.io 
  15.  * @GitHub https://github.com/nateshao 
  16.  * @Gitee https://gitee.com/nateshao 
  17.  * Description: 登錄攔截器 
  18.  */ 
  19. public class LoginInterceptor implements HandlerInterceptor { 
  20.     @Override 
  21.     public boolean preHandle(HttpServletRequest request, 
  22.                              HttpServletResponse response, Object handler) throws Exception { 
  23.         // 獲取請求的URL 
  24.         String url = request.getRequestURI(); 
  25.         // URL:除了login.jsp是可以公開訪問的,其它的URL都進(jìn)行攔截控制 
  26.         if (url.indexOf("/login") >= 0) { 
  27.             return true
  28.         } 
  29.         // 獲取Session 
  30.         HttpSession session = request.getSession(); 
  31.         User user = (User) session.getAttribute("USER_SESSION"); 
  32.         // 判斷Session中是否有用戶數(shù)據(jù),如果有,則返回true,繼續(xù)向下執(zhí)行 
  33.         if (user != null) { 
  34.             return true
  35.         } 
  36.         // 不符合條件的給出提示信息,并轉(zhuǎn)發(fā)到登錄頁面 
  37.         request.setAttribute("msg""您還沒有登錄,請先登錄!"); 
  38.         request.getRequestDispatcher("/WEB-INF/jsp/login.jsp"
  39.                 .forward(request, response); 
  40.         return false
  41.     } 
  42.  
  43.     @Override 
  44.     public void postHandle(HttpServletRequest request, 
  45.                            HttpServletResponse response, Object handler, 
  46.                            ModelAndView modelAndView) throws Exception { 
  47.     } 
  48.  
  49.     @Override 
  50.     public void afterCompletion(HttpServletRequest request, 
  51.                                 HttpServletResponse response, Object handler, Exception ex) 
  52.             throws Exception { 
  53.     } 

UserController.java

  1. package com.nateshao.controller; 
  2.  
  3. import com.nateshao.po.User
  4. import org.springframework.stereotype.Controller; 
  5. import org.springframework.ui.Model; 
  6. import org.springframework.web.bind.annotation.RequestMapping; 
  7. import org.springframework.web.bind.annotation.RequestMethod; 
  8. import javax.servlet.http.HttpSession; 
  9.  
  10. /** 
  11.  * @date Created by 邵桐杰 on 2021/10/22 12:47 
  12.  * @微信公眾號 程序員千羽 
  13.  * @個人網(wǎng)站 www.nateshao.cn 
  14.  * @博客 https://nateshao.gitee.io 
  15.  * @GitHub https://github.com/nateshao 
  16.  * @Gitee https://gitee.com/nateshao 
  17.  * Description: 
  18.  */ 
  19. @Controller 
  20. public class UserController { 
  21.     /** 
  22.      * 向用戶登錄頁面跳轉(zhuǎn) 
  23.      */ 
  24.     @RequestMapping(value = "/login", method = RequestMethod.GET) 
  25.     public String toLogin() { 
  26.         return "login"
  27.     } 
  28.  
  29.     /** 
  30.      * 用戶登錄 
  31.      */ 
  32.     @RequestMapping(value = "/login", method = RequestMethod.POST) 
  33.     public String login(User user, Model model, HttpSession session) { 
  34.         // 獲取用戶名和密碼 
  35.         String username = user.getUsername(); 
  36.         String password = user.getPassword(); 
  37.         // 此處模擬從數(shù)據(jù)庫中獲取用戶名和密碼后進(jìn)行判斷 
  38.         if (username != null && username.equals("nateshao"
  39.                 && password != null && password.equals("123456")) { 
  40.             // 將用戶對象添加到Session 
  41.             session.setAttribute("USER_SESSION"user); 
  42.             // 重定向到主頁面的跳轉(zhuǎn)方法 
  43.             return "redirect:main"
  44.         } 
  45.         model.addAttribute("msg""用戶名或密碼錯誤,請重新登錄!"); 
  46.         return "login"
  47.     } 
  48.  
  49.     /** 
  50.      * 向用戶主頁面跳轉(zhuǎn) 
  51.      */ 
  52.     @RequestMapping(value = "/main"
  53.     public String toMain() { 
  54.         return "main"
  55.     } 
  56.  
  57.     /** 
  58.      * 退出登錄 
  59.      */ 
  60.     @RequestMapping(value = "/logout"
  61.     public String logout(HttpSession session) { 
  62.         // 清除Session 
  63.         session.invalidate(); 
  64.         // 重定向到登錄頁面的跳轉(zhuǎn)方法 
  65.         return "redirect:login"
  66.     } 

main.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8" 
  2.      pageEncoding="UTF-8"%> 
  3. <html> 
  4. <head> 
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
  6. <title>系統(tǒng)主頁</title> 
  7. </head> 
  8. <body> 
  9.     當(dāng)前用戶:${USER_SESSION.username}   
  10.     <a href="${pageContext.request.contextPath }/logout">退出</a>   
  11. </body> 
  12. </html> 

驗(yàn)證

瀏覽器輸入:http://localhost:8080/110_springmvc_interceptor_war_exploded/main

輸入用戶名密碼

總結(jié)

這一篇文章主要對Spring MVC中的攔截器使用進(jìn)行了詳細(xì)講解。

首先介紹了如何在Spring MVC項(xiàng)目中定義和配置攔截器,然后詳細(xì)講解了單個攔截器和多個攔截器的執(zhí)行流程,最后通過一個用戶登錄權(quán)限驗(yàn)證的應(yīng)用案例演示了攔截器的實(shí)際應(yīng)用。 

最后我們可以對Spring MVC中攔截器的定義和配置方式有一定的了解,能夠熟悉攔截器的執(zhí)行流程,并能夠掌握攔截器的使用。

 

責(zé)任編輯:武曉燕 來源: 程序員千羽
相關(guān)推薦

2022-02-07 11:01:23

ZooKeeper

2022-01-02 08:43:46

Python

2021-10-26 10:40:26

代理模式虛擬

2021-12-04 22:05:02

Linux

2022-05-17 08:02:55

GoTryLock模式

2022-06-30 22:53:18

數(shù)據(jù)結(jié)構(gòu)算法

2021-08-01 07:19:16

語言OpenrestyNginx

2021-07-02 08:51:29

源碼參數(shù)Thread

2021-07-16 22:43:10

Go并發(fā)Golang

2021-09-28 08:59:30

復(fù)原IP地址

2023-03-13 21:38:08

TCP數(shù)據(jù)IP地址

2021-10-14 10:22:19

逃逸JVM性能

2021-10-27 09:59:35

存儲

2022-04-12 08:30:52

回調(diào)函數(shù)代碼調(diào)試

2023-11-01 09:07:01

Spring裝配源碼

2022-03-11 10:21:30

IO系統(tǒng)日志

2022-10-20 07:39:26

2021-04-29 10:18:18

循環(huán)依賴數(shù)組

2021-10-29 07:35:32

Linux 命令系統(tǒng)

2022-11-14 08:17:56

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號