Spring Boot無法訪問靜態資源(css,js等)的問題
阿新 • • 發佈:2019-02-01
規範專案結構
使用官方預設的掃描路徑。畢竟框架的好處就是嚴格按照要求搭好之後幾乎所有的操作都會變得簡單,一句話概括就是一勞永逸
spring boot對靜態資源的預設掃描路徑是:
classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources
spring.mvc.static-path-pattern=/resources/static/*
個人比較建議用下面方式(兩者取其一):
@Configuration public class MyWebAppConfigurer extends WebMvcConfigurerAdapter { Logger logger= LoggerFactory.getLogger(LoginInterceptor.class); /** * 資源處理器 * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { logger.info("addResourceHandlers"); // registry.addResourceHandler("/swagger-ui.html") // .addResourceLocations("classpath:/META-INF/resources/");// registry.addResourceHandler("/webjars/**") // .addResourceLocations("classpath:/META-INF/resources/webjars/"); //將所有/static/** 訪問都對映到classpath:/static/ 目錄下 registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); super.addResourceHandlers(registry);} }
主要加上:
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
如果以現還是不行,那麼在pox.xml中(maven專案中)加上:
<resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include></includes> <filtering>true</filtering> </resource>
這樣就可以了
其它可參考:
https://blog.csdn.net/yu514950381/article/details/78015088