在SpringBoot項目中出現了靜態資源文件無法訪問的情況,明明路徑都正確,但是就訪問不了
springboot訪問靜態資源,默認有兩個默認目錄:
一個是 src/mian/resource目錄
一個是 ServletContext 根目錄下(src/main/webapp)
1.查看是否開啟了靜態資源文件放行
有三種方式可以實現靜態文件放行,任選其一即可
1.1 在application.properties配置靜態文件放行
spring.web.resources.static-locations=classpath:/static/
1.2 在application.yml配置靜態文件放行
spring:
resources:
static-locations: classpath:/static/
1.3 實現WebMvcConfigurer接口實現靜態文件放行
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
}
如果還是不能訪問靜態文件,就需要檢查maven是否將靜態文件打包進target目錄了
2. 查看maven是否將靜態文件打包進target目錄
像這種情況就是沒有將靜態文件打包進target目錄,需要修改maven的配置
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>static/**</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
這樣就可以訪問靜態資源文件了