大家好,又见面了,我是你们的朋友全栈君。
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");
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/160971.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...