SpringBoot項目中如何實現登錄攔截器


什么是攔截器?

攔截器(Interceptor),主要完成請求參數的解析、將頁面表單參數賦給值棧中相應屬性、執行功能檢驗、程序異常調試等工作。(百度百科)

 

前期准備

login.html登錄頁

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <!--
 5         使用了Thymeleaf模板引擎之后,所有的靜態資源都要使用Thymeleaf提供的表達式來獲取
 6         例如:
 7             ${} 變量
 8             #{} message
 9             @{} url
10             ~{}
11         不然的話,前端就會識別加載不出來這些引用的靜態資源
12 
13         尤其要注意的是:springboot中的template目錄下的文件不能通過瀏覽器去直接請求,而是
14         要通過服務器內部去轉發才能獲取到
15      -->
16     <meta charset="UTF-8">
17     <title>登錄頁面</title>
18     <link rel="stylesheet" th:href="@{/css/style.css}" />
19     <script type="text/javascript" th:src="@{/js/jquery-3.4.1.js}"></script>
20     <script type="text/javascript">
21         <!--入口函數    -->
22         $(function () {
23             var $errorSpan = $("#error-span");
24             $("#submit_a").click(function () {
25                 var $userName = $("#userName").val();
26                 var $password = $("#password").val();
27                 var $data = JSON.stringify({
28                     "userName": $userName,
29                     "password": $password
30                 });
31                 // 發送Ajax請求進行登錄
32                 $.ajax({
33                     method: "POST",
34                     url: "/user/login",
35                     data: $data,
36                     dataType: "json",
37                     contentType: "application/json",
38                     success: function (data) {
39                         if (data === "yes") {
40                             window.location.href = "/main.html";
41                         } else {
42                             $errorSpan.html("用戶名或密碼錯誤");
43                         }
44                     },
45                     error: function (data) {
46                         alert(data);
47                         alert("服務器繁忙");
48                     }
49                 });
50             });
51         });
52     </script>
53 </head>
54 <body>
55 <!-- partial:index.partial.html -->
56 <div class="login-box">
57     <h2>登錄系統</h2>
58     <form th:action="@{/user/login}" method="post">
59         <div class="user-box">
60             <input type="text" id="userName" name="userName" required="" autocapitalize="none"/>
61             <label>用戶名</label>
62         </div>
63         <div class="user-box">
64             <input type="password" id="password" name="password" required="" autocapitalize="none"/>
65             <label>密碼</label>
66         </div>
67         <a href="javascript:void(0);" id="submit_a">
68             <span></span>
69             <span></span>
70             <span></span>
71             <span></span>
72             進入系統
73         </a>
74         &nbsp;
75         <span id="error-span" th:text="${msg}" style="color: red"></span>
76     </form>
77 </div>
78 </body>
79 </html>

 

進入正題——SpringBoot項目中如何實現登錄攔截器

一、首先,我們需要編寫一個登錄攔截器類,將該類實現HandlerInterceptor接口,該接口是spring.web.servlet包下的

 LoginInterceptor類

 1 public class LoginInterceptor implements HandlerInterceptor {
 2     @Override
 3     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 4         Object user = request.getSession().getAttribute("user");
 5         if (user == null) {
 6             // 沒有登錄,讓用戶直接去登錄頁
 7             request.setAttribute("msg", "沒有權限,請登錄");
 8             request.getRequestDispatcher("/login.html").forward(request, response);
 9             return false;
10         }
11         return true;
12     }
13 
14     @Override
15     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
16 
17     }
18 
19     @Override
20     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
21 
22     }
23 }

二、然后我們需要在我們的WebMVC配置類中配置攔截器

MyMVCConfig類

 1 package com.lzp.config;
 2 
 3 import org.springframework.context.annotation.Configuration;
 4 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
 5 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
 6 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
 7 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 8 
 9 /**
10  * @Author LZP
11  * @Date 2021/4/19 9:39
12  * @Version 1.0
13  * <p>
14  * 自定義擴展MVC類
15  * 如果我們想要擴展功能,就比如說我們要配置一個屬於自己的視圖解析器類,就可以新建一個類,
16  * 只要將該類實現ViewResolver接口即可,最后再將自己的視圖解析器類作為Bean配置到Spring容
17  * 器中(這里我們已經不用配置文件了,現在只要在一個類上加@Configuration注解的類功能就等
18  * 同於之前的配置文件)
19  */
20 @Configuration
21 public class MyMVCConfig implements WebMvcConfigurer {
22 
23     /**
24      * 配置視圖控制器
25      * @param registry
26      */
27     @Override
28     public void addViewControllers(ViewControllerRegistry registry) {
29         registry.addViewController("/").setViewName("login");
30         registry.addViewController("/login.html").setViewName("login");
31         registry.addViewController("/main.html").setViewName("main");
32     }
33 
34     /**
35      * 配置攔截器
36      * @param registry
37      */
38     @Override
39     public void addInterceptors(InterceptorRegistry registry) {
40         // 登錄攔截
41         registry.addInterceptor(new LoginInterceptor())
42                 .addPathPatterns("/**")
43                 // 注意:不要過濾static目錄下的所有,不然可能會有問題
44                 .excludePathPatterns("/css/**", "/js/**", "/img/**", "/user/login", "/", "/login.html");
45     }
46 
47 }

三、測試


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM