Spring Boot 默認採用 WebMvcAutoConfiguration
類中配置的默認屬性,但在項目開發過程當中,默認配置可能沒法知足實際需求。css
默認狀況下spring boot 將 /** 映射到 classpath 中如下路徑:html
classpath:/static classpath:/public classpath:/resources classpath:/META-INF/resources
默認狀況下,將靜態資源直接放在以上四個路徑下,能夠直接進行訪問,如:spring
/static/index1.html /public/index2.html /resources/index3.html
分別執行請求:mvc
http://localhost:8080/index1.html http://localhost:8080/index2.html http://localhost:8080/index3.html
則分別返回index1.html、index2.html 、index3.html
內容,說明spring boot 會在以上文件夾中查找對應資源並返回。app
spring boot 默認設置了4個文件路徑用於存放靜態資源,可是在實際開發中會對靜態資源進行分組管理,對於這種狀況,spring boot 默認是沒法訪問到的,如:ide
/static/css/style.css /static/js/main.js /static/img/icon.png
分別請求以上四個文件,會返回404。緣由在於spring boot 默認只在/static /resources /public /META-INF/resources
四個路徑中進行查找,並不包含子路徑。spa
WebMvcConfigurerAdapter
如將全部/static/**
靜態資源訪問都映射到classpath:/static/
路徑下:code
/** * Author: yxguang.<br> * Email: yxguang1988@gmail.com<br> * Description: 靜態資源配置<br> */ @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { super.addResourceHandlers(registry); registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } }
# spring.mvc.static-path-pattern=/** # Path pattern used for static resources. spring.mvc.static-path-pattern=/static/** #spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ # Locations of static resources.
這個配置會影響默認的/**,例如修改成/static/**後,只能映射如/static/js/main.js這樣的請求(修改前是/js/main.js)。這個配置只能寫一個值,不像大多數能夠配置多個用逗號隔開的。
經過spring.mvc.static-path-pattern這種方式配置,會使Spring Boot的默認配置失效,也就是說,/public /resources 等默認配置不能使用。 配置中配置了靜態模式爲/static/,就只能經過/static/來訪問。htm