springboot2.x使用interceptor之后静态资源文件加载问题
By:Roy.LiuLast updated:2019-07-31
在使用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 { } }
From:一号门
Previous:centos下安装pip, psutil容易踩的坑.
COMMENTS