Springboot拦截器配置

admin
2022-03-10 / 0 评论 / 43 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年03月26日,已超过102天没有更新,若内容或图片失效,请留言反馈。

Springboot拦截器配置

1、拦截器配置,主要实现HandlerInterceptor接口

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * @description: 拦截器,配合FamilyWebConfig 配置使用
 * @author: <a href="mailto:batis@foxmail.com">清风</a>
 * @date: 2022/3/10 22:36
 * @version: 1.0
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<Object> objUser = new ThreadLocal<>();
    @Override
    public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginusr = request.getSession().getAttribute("LOGIN_USR");
        if(loginusr != null){
            objUser.set(loginusr);
            //登录了才能访问
            return true;
        }else{
            //没登录,跳转去登录
            return  false;
        }

    }
}

由于拦截器需要配合web配置使用,因此创建web配置。

2、web配置主要实现WebMvcConfigurer接口

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @description: WEB配置
 * @author: <a href="mailto:batis@foxmail.com">清风</a>
 * @date: 2022/3/10 22:40
 * @version: 1.0
 */
public class FamilyWebConfig implements WebMvcConfigurer {

    @Autowired
    LoginUserInterceptor loginUserInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginUserInterceptor).addPathPatterns("/**");
    }
}
1

评论 (0)

取消