1、靜態資源路徑是指系統可以直接訪問的路徑,且路徑下的所有文件均可被用戶通過瀏覽器直接讀取。
2、在Springboot中默認的靜態資源路徑有:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
3、在Springboot中可以直接在配置文件中覆蓋默認的靜態資源路徑的配置信息:
#自定義的屬性,指定了一個路徑,注意要以/結尾
web.upload-path=D:/temp/study13/
#表示所有的訪問都經過靜態資源路徑 spring.mvc.static-path-pattern=/**
#覆蓋默認配置,所以需要將默認的也加上否則static、public等這些路徑將不能被當作靜態資源路徑
#在最末尾的file:${web.upload-path}中的file:表示是一個具體的硬盤路徑,其他的使用classpath指的是系統環境變量
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
4、在SpringBoot開發中,可以在Java代碼中覆蓋默認靜態資源配置
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if(!registry.hasMappingForPattern("/static/**")){ registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } super.addResourceHandlers(registry); } }
5、由於Spring Boot 默認資源路徑配置的問題,使用IDEA開發Spring Boot應用時,會導致一個問題————瀏覽器、編輯器 不能同時訪問 JS 等資源的問題。這時往往通過配置 4 中的代碼,來實現同時訪問資源文件的效果
參考知識林:http://www.zslin.com/web/article/detail/23