springboot2.x使用interceptor之后静态资源文件加载问题

在使用spring boot 2.x 的过程中,如果使用了interceptor来做权限拦截,很有可能你会发现原来能正常请求的资源文件css,js,images等都不能用了。如果没有加这个拦截器之前,所有的都是好的。一般在开发过程中,很多人估计都是先开发功能,最后再加权限拦截(当然如果采用第三方权限框架比如shiro等,不存在这问题), 尝试过修改application.properties增加静态资源文件地址,结果没用。最后还是在代码里面配置才生效.

程序代码 程序代码


@Configuration
public class AppConfig extends WebMvcConfigurationSupport {
    
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ClientTokenInterceptor()).addPathPatterns("/server/**").excludePathPatterns("/login/**", "/schedule/collect/info");
    }
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        super.addViewControllers(registry);        
        registry.addViewController("/").setViewName("forward:/login");
    }
    /*重写这个是重点. 可以根据自己需要增加多个地址.*/
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**", "/images/**", "/css/**", "/js/**", "/fonts/**", "/font-awesome/**")
                .addResourceLocations(
                    "classpath:/META-INF/resources/webjars/",
                    "classpath:/static/mosquitto/"                  
                );
    }

}


拦截器代码
程序代码 程序代码


public class ClientTokenInterceptor implements HandlerInterceptor  {
    
    private Logger logger = LoggerFactory.getLogger(this.getClass());    
    
    
    @SuppressWarnings({ "rawtypes", "unused" })
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {  
         //logger.info(request.getRequestURI());
         request.setAttribute("startTime", System.currentTimeMillis());
         Object user = request.getSession().getAttribute("loginUser");
         if (user == null) {
             request.getRequestDispatcher("/login").forward(request, response);
             return false;
         } else {
             return true;
         }        
    }    
    

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)throws Exception {
        long beginTime = (Long)request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();        
        //logger.info("complete url {}, total cost:{} " ,request.getRequestURI(), (endTime - beginTime));
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
        
    }
  
}




除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: springboot
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.