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

springboot2.3.4版本配置拦截器(不会配的,样式失效的看过来)

程序员文章站 2022-10-03 13:55:19
我使用的是springboot2.3.4,注意要实现HandlerInterceptor接口@Configurationpublic class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response,...

我使用的是springboot2.3.4,注意要实现HandlerInterceptor接口

@Configuration
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        if(request.getSession().getAttribute("user") == null){
            response.sendRedirect("/admin");
            return false;
        }
        return true;
    }
}

然后将拦截器配置到springboot中

@Configuration
public class webConfig implements WebMvcConfigurer {  //extends WebMvcConfigurationSupport   //implements WebMvcConfigurer
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin")
                .excludePathPatterns("/admin/login");
    }

//这里配置不要拦截静态资源
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {        registry.addResourceHandler("/static/**").addResourceLocations("/static/");

    }
}

还要注意静态资源的引用格式
比如:

<link rel="stylesheet" href="../static/css/me.css" th:href="@{/css/me.css}">

本文地址:https://blog.csdn.net/DoMyBestintheworld/article/details/109256865