SpringBoot mvc拦截器配置

该文章展示了如何在SpringMVC中配置拦截器以实现对用户登录状态的检查。`MyWebConfig`类定义了一个拦截器注册器,所有请求会被`LoginUserInterceptor`拦截,除了特定排除的URL。`LoginUserInterceptor`在预处理阶段检查用户是否已登录,如果未登录则重定向到登录页面。
摘要由CSDN通过智能技术生成

WebConfig

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;

/**
 * User: ldj
 * Date: 2022/10/12
 * Time: 10:37
 * Description: 访问order服务,都要经过拦截器
 */

@Configuration
public class MyWebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginUserInterceptor loginUserInterceptor;

    /**
     * 根据请求url进行配置,/**代表当前项目任意请求到达目标方法前都会被拦截审核,是否放行
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginUserInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/order/order/status/**",
                        "/mq/message/update/consumed/**",
                        "/payed/notify");
    }
}

Interceptor

import com.atguli.common.constant.AuthServerConstant;
import com.atguli.common.vo.MemberRespVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * User: ldj
 * Date: 2022/10/12
 * Time: 10:31
 * Description: 将拦截器作为组件交给spring容器,要让拦截器组件生效,
 * 还需配置WebMvcConfigurer,重写addInterceptors方法添加拦截器组件 //interceptor.path.uris=/kill,/**
 */

@Component
@RefreshScope
public class LoginUserInterceptor implements HandlerInterceptor {

    //拦截器存储当前线程共享变量数据
    public static ThreadLocal<MemberRespVO> threadLocal = new ThreadLocal<>();

    //添加需要拦截的请求uri,也可以在WebConfig配置
    @Value("#{'${spring.interceptor.uris}'.split(',')}")
    private List<String> uris;

    /**
     * 在请求到达目标方法之前拦截业务判断,是否放行请求?
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = false;

        if (uris.size() != 0) {
            for (String ur : uris) {
                if (antPathMatcher.match(ur, uri)) {
                    match = true;
                    break;
                }
            }
        }

        if (match) {
            //当前请求需要用户登录才能放行,默认拿到Cookie的sessionId
            MemberRespVO loginUser = (MemberRespVO) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
            if (loginUser != null) {
                //将用户的登录信息存入threadLocal,为执行当前请求的线程所共享
                threadLocal.set(loginUser);
                return true;
            } else {
                //没登录,要去登录
                request.getSession().setAttribute("msg", "请先登录再访问");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }
        }
        return true;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值