Springboot筆記<5>靜態資源訪問
靜態資源訪問
靜態資源目錄
請求進來,先去找Controller看能不能處理。不能處理的所有請求又都交給靜態資源處理器。靜態資源也找不到則響應404頁面。如果靜態目錄中存在a.png,訪問localhost:8080/a.png也不會訪問到a.png,而是會得到字串"student"。因為請求進來,先去找Controller看能不能處理。不能處理的所有請求又都交給靜態資源處理器。
@Slf4j @RestController public class StudentController { @RequestMapping("/a.png") public String handle02() { return "student"; } }
WebMvcAutoConfiguration
類自動為我們註冊瞭如下目錄為靜態資源目錄(favicon.ico,html等),也就是說直接可訪問到資源的目錄。優先順序從高到低分別是:
- classpath:/META-INF/resources/
- classpath:/resources/
- classpath:/static/
- classpath:/public/
- /當前專案的根路徑(resources)
WebMvcAutoConfiguration註冊的對應的主頁:
- classpath:/META-INF/resources/index.html
- classpath:/resources/index.html
- classpath:/static/index.html
- classpath:/public/index.html
- /index.html
從上到下。所以,如果static裡面有個index.html,public下面也有個index.html,則優先會載入static下面的index.html。
靜態資源訪問字首
spring:
mvc:
static-path-pattern: /res/**
web:
resources:
static-locations: [classpath:/haha/]
當前專案 + static-path-pattern + 靜態資源名 = 靜態資原始檔夾下找
例如原先訪問地址為{http://localhost:9999/a.png
自動對映 webjars
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
訪問地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 後面地址要按照依賴裡面的包路徑 <artifactId>,<version>。
welcomePage
-
靜態資源路徑下 index.html
-
- 可以配置靜態資源路徑
- 但是不可以配置靜態資源的訪問字首。否則導致 index.html不能被預設訪問
-
配置1依然可以通過ip+port訪問welcomePage
-
配置2不能可以通過ip+port訪問welcomePage,只能ip+port/index.html
#配置1
spring:
web:
resources:
static-locations: [classpath:/haha/]
#配置2
spring:
mvc:
static-path-pattern: /res/**
web:
resources:
static-locations: [classpath:/haha/]
favicon.ico
favicon.ico 放在靜態資源目錄下即可,增加訪問字首會使圖示失效
靜態資源配置原理
- SpringBoot啟動預設載入 xxxAutoConfiguration 類(自動配置類)
- SpringMVC功能的自動配置類 WebMvcAutoConfiguration,生效
SpringBoot啟動會預設載入很多xxxAutoConfiguration類(自動配置類),其中SpringMVC的大都數功能都集中在WebMvcAutoConfiguration類中,根據條件ConditionalOnxxx註冊類物件;WebMvcAutoConfiguration滿足以下ConditionalOnxxx條件,類是生效的,並把其物件註冊到容器中。
未經作者同意請勿轉載
本文來自部落格園作者:aixueforever,原文連結:https://www.cnblogs.com/aslanvon/p/15715163.html