欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Springboot使用HandlerInterceptor拦截用户登录

程序员文章站 2022-05-07 19:01:56
拦截器:@Aspect@Componentpublic class LoginInterceptor implements HandlerInterceptor { private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse...

拦截器:


@Aspect
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("-----------------preHandle");
        UserInfo user = (UserInfo)request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        logger.info(request.getRequestURI().toString());
        if (user == null || user.equals(""))  {
            response.sendRedirect("/login");
            logger.info("请先登录");
            return false;
        }
        return true;
    }
}

Config:

@Configuration
public class WebConfigurer implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).
                addPathPatterns("/**")
                .excludePathPatterns("/login")
                .excludePathPatterns("/static/**");
    }

}

如果是新项目的话,把aop的maven加进去:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

本文地址:https://blog.csdn.net/xianyun1992/article/details/107270652