<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          SpringBoot 實現(xiàn)登錄攔截器(實戰(zhàn)版)

          共 5382字,需瀏覽 11分鐘

           ·

          2021-08-10 15:59

          微信搜索逆鋒起筆關(guān)注后回復編程pdf
          領(lǐng)取編程大佬們所推薦的 23 種編程資料!

          作者:Kant101

          https://blog.csdn.net/qq_27198345/article/details/111401610

          文章目錄


            • 3.1、訪問 localhost:8081/index 頁面:

            • 3.2、正確輸入用戶名和密碼登錄

            • 3.3、再次訪問 localhost:8081/index

            • 1.1、實現(xiàn) HandlerInterceptor 接口

            • 1.2、實現(xiàn) WebMvcConfigurer 接口,注冊攔截器

            • 1.3、保持登錄狀態(tài)

            • 1、SpringBoot 實現(xiàn)登錄攔截的原理


            • 2、代碼實現(xiàn)及示例

            • 3、效果驗證

          對于管理系統(tǒng)或其他需要用戶登錄的系統(tǒng),登錄驗證都是必不可少的環(huán)節(jié),在 SpringBoot 開發(fā)的項目中,通過實現(xiàn)攔截器來實現(xiàn)用戶登錄攔截并驗證。

          1、SpringBoot 實現(xiàn)登錄攔截的原理

          SpringBoot 通過實現(xiàn)HandlerInterceptor接口實現(xiàn)攔截器,通過實現(xiàn)WebMvcConfigurer接口實現(xiàn)一個配置類,在配置類中注入攔截器,最后再通過 @Configuration 注解注入配置.

          1.1、實現(xiàn)HandlerInterceptor接口

          實現(xiàn)HandlerInterceptor接口需要實現(xiàn) 3 個方法:preHandle、postHandle、afterCompletion.

          3 個方法各自的功能如下:

          package blog.interceptor;

          import blog.entity.User;
          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 UserLoginInterceptor implements HandlerInterceptor {

          /***
          * 在請求處理之前進行調(diào)用(Controller方法調(diào)用之前)
          */

          @Override
          public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          System.out.println("執(zhí)行了攔截器的preHandle方法");
          try {
          HttpSession session = request.getSession();
          //統(tǒng)一攔截(查詢當前session是否存在user)(這里user會在每次登錄成功后,寫入session)
          User user = (User) session.getAttribute("user");
          if (user != null) {
          return true;
          }
          response.sendRedirect(request.getContextPath() + "login");
          } catch (Exception e) {
          e.printStackTrace();
          }
          return false;
          //如果設置為false時,被請求時,攔截器執(zhí)行到此處將不會繼續(xù)操作
          //如果設置為true時,請求將會繼續(xù)執(zhí)行后面的操作
          }

          /***
          * 請求處理之后進行調(diào)用,但是在視圖被渲染之前(Controller方法調(diào)用之后)
          */

          @Override
          public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
          System.out.println("執(zhí)行了攔截器的postHandle方法");
          }

          /***
          * 整個請求結(jié)束之后被調(diào)用,也就是在DispatchServlet渲染了對應的視圖之后執(zhí)行(主要用于進行資源清理工作)
          */

          @Override
          public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
          System.out.println("執(zhí)行了攔截器的afterCompletion方法");
          }
          }

          preHandle在 Controller 之前執(zhí)行,因此攔截器的功能主要就是在這個部分實現(xiàn):

          1. 檢查 session 中是否有user對象存在;

          2. 如果存在,就返回true,那么 Controller 就會繼續(xù)后面的操作;

          3. 如果不存在,就會重定向到登錄界面
            就是通過這個攔截器,使得 Controller 在執(zhí)行之前,都執(zhí)行一遍preHandle.

          1.2、實現(xiàn)WebMvcConfigurer接口,注冊攔截器

          實現(xiàn)WebMvcConfigurer接口來實現(xiàn)一個配置類,將上面實現(xiàn)的攔截器的一個對象注冊到這個配置類中.

          package blog.config;

          import blog.interceptor.UserLoginInterceptor;
          import org.springframework.context.annotation.Configuration;
          import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
          import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
          import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

          @Configuration
          public class LoginConfig implements WebMvcConfigurer {

          @Override
          public void addInterceptors(InterceptorRegistry registry) {
          //注冊TestInterceptor攔截器
          InterceptorRegistration registration = registry.addInterceptor(new UserLoginInterceptor());
          registration.addPathPatterns("/**"); //所有路徑都被攔截
          registration.excludePathPatterns( //添加不攔截路徑
          "/login", //登錄路徑
          "/**/*.html", //html靜態(tài)資源
          "/**/*.js", //js靜態(tài)資源
          "/**/*.css" //css靜態(tài)資源
          );
          }
          }

          將攔截器注冊到了攔截器列表中,并且指明了攔截哪些訪問路徑,不攔截哪些訪問路徑,不攔截哪些資源文件;最后再以 @Configuration 注解將配置注入。

          1.3、保持登錄狀態(tài)

          只需一次登錄,如果登錄過,下一次再訪問的時候就無需再次進行登錄攔截,可以直接訪問網(wǎng)站里面的內(nèi)容了。

          在正確登錄之后,就將user保存到session中,再次訪問頁面的時候,登錄攔截器就可以找到這個user對象,就不需要再次攔截到登錄界面了.

          @RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET)
          public String index(Model model, HttpServletRequest request) {
          User user = (User) request.getSession().getAttribute("user");
          model.addAttribute("user", user);
          return "users/index";
          }

          @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
          public String loginIndex() {
          return "users/login";
          }

          @RequestMapping(value = {"/login"}, method = RequestMethod.POST)
          public String login(@RequestParam(name = "username")String username, @RequestParam(name = "password")String password,
          Model model, HttpServletRequest request)
          {
          User user = userService.getPwdByUsername(username);
          String pwd = user.getPassword();
          String password1 = MD5Utils.md5Code(password).toUpperCase();
          String password2 = MD5Utils.md5Code(password1).toUpperCase();
          if (pwd.equals(password2)) {
          model.addAttribute("user", user);
          request.getSession().setAttribute("user", user);
          return "redirect:/index";
          } else {
          return "users/failed";
          }
          }

          2、代碼實現(xiàn)及示例

          代碼實現(xiàn)如上所示。

          在登錄成功之后,將user信息保存到session中,下一次登錄時瀏覽器根據(jù)自己的SESSIONID就可以找到對應的session,就不要再次登錄了,可以從 Chrome 瀏覽器中看到。

          3、效果驗證

          3.1、訪問 localhost:8081/index 頁面:


          被重定向到了 localhost:8081/login,實現(xiàn)了登錄攔截。

          3.2、正確輸入用戶名和密碼登錄

          3.3、再次訪問 localhost:8081/index


          沒有再次被登錄攔截器攔截,證明可以保持登錄.

          逆鋒起筆是一個專注于程序員圈子的技術(shù)平臺,你可以收獲最新技術(shù)動態(tài)、最新內(nèi)測資格、BAT等大廠大佬的經(jīng)驗增長自身、學習資料職業(yè)路線、賺錢思維,微信搜索逆鋒起筆關(guān)注!

          基于 SpringBoot 仿豆瓣完整源碼分享!
          面試官:為什么 SpringBoot 的 jar 可以直接運行?
          推薦一款基于 SpringBoot 的接口快速開發(fā)框架
          前后端分離 Spring Boot + Vue 開發(fā)網(wǎng)易云、QQ音樂(附源碼)!
          這 5 個能掙錢的 SpringBoot 項目,真 TMD 香!

          瀏覽 25
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  天堂精品一区二区三区 | 色婷婷黄色无码视频 | 色女孩国产视频 | 黄金网站免费大全入口 | 操逼视频五月天 |