簡單使用攔截器實現登錄+攔截器


攔截器

參考b站狂神視頻

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

攔截器(Interceptor):它依賴於web框架,在SpringMVC中就是依賴於SpringMVC框架。在實現上,基於Java的反射機制,屬於面向切面編程(AOP)的一種運用,就是在service或者一個方法前,調用一個方法,或者在方法后,調用一個方法,比如動態代理就是攔截器的簡單實現,在調用方法前打印出字符串(或者做其它業務邏輯的操作),也可以在調用方法后打印出字符串,甚至在拋出異常的時候做業務邏輯的操作。由於攔截器是基於web框架的調用,因此可以使用Spring的依賴注入(DI)進行一些業務操作,同時一個攔截器實例在一個controller生命周期之內可以多次調用。但是缺點是只能對controller請求進行攔截,對其他的一些比如直接訪問靜態資源的請求則沒辦法進行攔截處理。

攔截器重寫三個方法,詳見參考,其與過濾器的區別參考 https://blog.csdn.net/zxd1435513775/article/details/80556034

為了解決 用戶可以不登陸便可進入主頁,這是不安全的,為了解決這個問題,便可使用攔截器。

一、新建登錄攔截器

LoginHandlerIntercepter.java

package com.example.employee_management.config;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @className: LoginHandlerIntercepter
* @description: 登錄攔截器
*/
public class LoginHandlerIntercepter implements HandlerInterceptor {

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

       //獲取登錄用戶的session
       Object loginUser=request.getSession().getAttribute("loginUser");

       //session不存在,即用戶尚未登錄
       if(loginUser==null){
           request.setAttribute("msg","請先登錄");
           //返回首頁
           request.getRequestDispatcher("/index.html").forward(request,response);

           return false;

      }else {
           return true;
      }

  }
}

二、在MVC配置類中添加登錄攔截器

MyMvcConfig.java

package com.example.employee_management.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* @className: MyMvcConfig
* @description: MVC 控制器 借助注解完成控制器而不用手動編寫
*/
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

   /**
    * MVC 添加首頁控制器
    *
    * @param registry
    */
   @Override
   public void addViewControllers(ViewControllerRegistry registry) {
       //這里 “/”和“/index.html”效果一樣,因為web項目默認頁是index.html
       registry.addViewController("/").setViewName("index");
       registry.addViewController("/index.html").setViewName("index");

       //添加用戶主頁
       registry.addViewController("/main.html").setViewName("dashboard");
  }


   /**
    * 將國際化組件放入ioc容器中
    *
    * @return
    */
   @Bean
   public LocaleResolver localeResolver() {
       return new MyLocaleResolver();
  }


   /**
    * 添加登錄攔截器
    * @param registry
    */
   @Override
   public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(new LoginHandlerIntercepter()).addPathPatterns("/**")//對所有請求進行攔截
              .excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");此路徑下請求的進行放行,可以是一些靜態資源
  }
}

三、修改登錄控制器:添加session來保證攔截器正常運行

LoginController.java

package com.example.employee_management.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

   @RequestMapping("/user/login")
   public String login(@RequestParam("username")String username,
                       @RequestParam("password")String password, Model model,
                       HttpSession session){

       //用戶名不為空且密碼正確 注意這里的數據是默認密碼為123456,便於調試
       if(!StringUtils.isEmpty(username) && "123456".equals(password)){
           session.setAttribute("loginUser",username);
           return "redirect:/main.html";
      }else {
           //用戶名或密碼錯誤
           model.addAttribute("msg","用戶名或密碼錯誤");
           return "index";
      }
  }
}

啟動項目后,在瀏覽器中輸入

localhost:8080/main.html

便會轉入到首頁(index.html),並且提示用戶尚未登錄。 在這里插入圖片描述 登錄攔截器的功能便已完成。

 


免責聲明!

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



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