SpringBoot登錄用戶權限攔截器

1. 創建自定義攔截器類並實現 HandlerInterceptor 接口

package com.xgf.online_mall.interceptor;

import com.xgf.online_mall.system.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

@Slf4j
@Component
public class UserLoginAuthInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.info(" ======== UserAuthInterceptor preHandle 登錄權限攔截器攔截");
    User user = (User) request.getSession().getAttribute("loginUser");
    //未登錄才判斷,登錄瞭直接放行
    if(user == null){
      //獲取訪問路徑
      String address = request.getRequestURI();
      log.info("======== 攔截,訪問路徑 address : {}", address);
      response.sendRedirect(request.getContextPath() + "/login.html");
      return false;

      /*String address = request.getRequestURI();
      log.info("======== 攔截,訪問路徑 address : {}", address);
      //不是登錄或者註冊頁面,就直接跳轉登錄界面
      if(!address.contains("login") && !address.contains("register")){
        //強制到登錄頁面
        response.sendRedirect(request.getContextPath() + "/login.html");
        //設置為false,不訪問controller
        return false;
      }*/
    }
    //其它模塊或者已經登錄,就直接放行
//    log.info("======== 已登錄 user = {}", user);
    return true;
  }


  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    log.info(" ===== UserAuthInterceptor postHandle");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    log.info("==== UserAuthInterceptor afterCompletion");

    //記錄日志 向文件裡面寫日志
    //獲取服務器記錄日志log文件所存放的目錄位置 -- tomcat下的真實路徑+log目錄
    String logdir = request.getServletContext().getRealPath("log");
    //路徑不存在就創建
    Path logdirPath = Paths.get(logdir);
    if(Files.notExists(logdirPath)){
      Files.createDirectories(logdirPath);
    }
    //目錄存在就將數據[字符]寫入 //存放日志的路徑+文件名
    Path logfile = Paths.get(logdir,"userlog.log");
    //logfile.toFile() paths轉換為File類型 true以追加的方式寫入
    BufferedWriter writer = new BufferedWriter(new FileWriter(logfile.toFile(),true));

    //獲取登錄用戶信息
    User user = (User)request.getSession().getAttribute("loginUser");
    //記錄user信息,存入日志
    writer.write(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " >> " + user +"\r\n");
    writer.flush();
    writer.close();
  }
}

2. 創建WebMvcConfigurer接口實現類,註冊並生效自定義的攔截器

import com.xgf.online_mall.constant.PathConstantParam;
import com.xgf.online_mall.interceptor.UserLoginAuthInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
@Slf4j
public class LoginConfig implements WebMvcConfigurer {
  @Autowired
  private UserLoginAuthInterceptor userLoginAuthInterceptor;

  /**
   * addInterceptors方法設置攔截路徑
   *   addPathPatterns:需要攔截的訪問路徑
   *   excludePathPatterns:不需要攔截的路徑,
   *   String數組類型可以寫多個用","分割
   * @param registry
   */
  @Override
  public void addInterceptors(InterceptorRegistry registry){
    log.info(" ======== LoginConfig.addInterceptors");
    //添加對用戶未登錄的攔截器,並添加排除項
    //error路徑,excludePathPatterns排除訪問的路徑在項目中不存在的時候,
    //springboot會將路徑變成 /error, 導致無法進行排除。
    registry.addInterceptor(userLoginAuthInterceptor)
        .addPathPatterns("/**")
        .excludePathPatterns("/js/**", "/css/**", "/img/**", "/plugins/**")
        .excludePathPatterns("/login.html", "/register.html", "/system/user/login", "/system/user/login", "/index")
        .excludePathPatterns("/error");
  }
 }

到此這篇關於SpringBoot登錄用戶權限攔截器的文章就介紹到這瞭,更多相關SpringBoot 用戶權限攔截器內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: