Bootstrap

Springboot项目添加拦截器

1.创建一个拦截器类,实现HandlerInterceptor接口,并实现preHandle方法:

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * @author: 
 * @Desc:
 * @create: 2024-11-24 19:52
 **/
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    
    //使用线程池管理登录用户信息,方便全局共享
    public static ThreadLocal<MemberRespVo>localUser=new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute!=null){
            localUser.set(attribute);
            return true;
        }else {
            //没登录就拦截重定向到登录页
            request.getSession().setAttribute("msg","请先登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;

        }
    }
}

2.创建一个OrderWebConfiguration,实现WebMvcConfigurer接口,将上面定义的拦截器,注册到webmvc当中,并指定要拦截的请求地址:

import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
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;

/**
 * @author: 
 * @Desc:
 * @create: 2024-11-24 19:55
 **/
@Configuration
public class OrderWebConfiguration implements WebMvcConfigurer {
    @Autowired
    private LoginUserInterceptor loginUserInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加拦截器和拦截地址
        registry.addInterceptor(loginUserInterceptor).addPathPatterns("/**");
    }
}

如此就实现添加一个拦截器,当系统检测到未登录,就拦截重定向到登录页面。

;