SpringBoot拦截器的设置

1.登录拦截实现HandlerInterceptor接口

public class LoginInterceptor implements HandlerInterceptor {
    /**
     *
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 处理器(url+controller),映射
     * @return 返回值为true,放行请求;返回值为false,拦截当前请求
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        User user = (User) request.getSession().getAttribute("user");
        // 用户没有登陆过
        if(null == user){
            response.sendRedirect("/web/login.html");
            return false;
        }

        return true;
    }
}

2.定义配置类取实现WebMvcConfigurer 接口,重写addInterceptors方法

// 加载当前的拦截器并进行注册
@Configuration
public class MyAppConfig implements WebMvcConfigurer {
    /**
     * 拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 创建拦截器对象
        HandlerInterceptor handlerInterceptor = new LoginInterceptor();

        // 白名单
        List<String> excludePath = new ArrayList<>();
        excludePath.add("/bootstrap3/**");
        excludePath.add("/css/**");
        excludePath.add("/images/**");
        excludePath.add("/js/**");
        excludePath.add("/web/register.html");
        excludePath.add("/web/login.html");
        excludePath.add("/web/product.html");
        excludePath.add("/users/login");
        excludePath.add("/users/register");
        excludePath.add("/index.html");

        registry.addInterceptor(handlerInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(excludePath);
    }

}

posted on 2022-01-25 15:18  玄凰寒  阅读(175)  评论(0编辑  收藏  举报

导航