服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - SpringBoot登录用户权限拦截器

SpringBoot登录用户权限拦截器

2021-08-26 11:35strive_day Java教程

这篇文章主要介绍了SpringBoot登录用户权限拦截器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1. 创建自定义拦截器类并实现 HandlerInterceptor 接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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接口实现类,注册并生效自定义的拦截器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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 用户权限拦截器内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_40542534/article/details/115025189

延伸 · 阅读

精彩推荐