目錄
- 一、首頁
- 1. 分析原始碼
- 2. 直接訪問首頁測驗
- 3. 通過請求跳轉到首頁
- 二、圖示設定
一、首頁
同樣在
WebMvcAutoConfugure類中的自動配置適配類WebMvcAutoConfigurationAdapter中有三個方法,是關于首頁的

1. 分析原始碼

首先是歡迎頁處理映射類WelcomePageHandler,它通過@Bean注解被注入到bean中,它通過兩種方式獲得資源路徑:
- 自定義的資源路徑
this.mvcProperties.getStaticPathPattern() - 呼叫
gerWelcomPage獲得資源路徑
其中getWelcomPage方法中,有個getStaticLocations方法,回傳的locations就是上述的四個靜態資源路徑
String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
"classpath:/META-INF/resources/":就是上述的webjars
"classpath:/resources/":reources目錄下的resources目錄,不存在自己新建
"classpath:/static/":resources目錄下的static目錄
"classpath:/public/":resources目錄下的public目錄,不存在自己新建

在getWelcomePage方法中還呼叫了getIndexHtml方法,用于配置首頁,位置就是上述locations的下的index.html
private Resource getIndexHtml(String location) {
return this.resourceLoader.getResource(location + "index.html");
}
總結:我們將首頁index.html檔案放置靜態資源四個目錄任意一個位置即可直接訪問加載
2. 直接訪問首頁測驗
我們可以把首頁index.html放入以下任意一個目錄
"classpath:/META-INF/resources/":就是上述的webjars
"classpath:/resources/":reources目錄下的resources目錄,不存在自己新建
"classpath:/static/":resources目錄下的static目錄
"classpath:/public/":resources目錄下的public目錄,不存在自己新建
這里在resource目錄下的public目錄下新建index.html表示首頁

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
<h1>首頁</h1>
</body>
</html>
然后運行主程式測驗,訪問localhost:8080,成功加載到了首頁

3. 通過請求跳轉到首頁
通常情況下,我們需要通過請求跳轉到首頁,因此我們需要寫一個controller進行視圖跳轉,那么這個頁面放在哪里呢?
在resource下,除了public、resource、staic三個靜態目錄,還有一個template目錄,因此,我們可以將我們的首頁放入該目錄下,通過請求加載到首頁
-
springboot專案默認是不允許直接訪問
templates下的檔案的,是受保護的, -
如果要訪問templates下的檔案,需要模板引擎的支持,推薦使用
thymeleaf,這里匯入thymeleaf依賴
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
然后,我們將上述index.html移入templates包中

然后再撰寫一個IndexController

package com.zsr.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
重新啟動主程式訪問測驗,訪問/index,成功顯示首頁

二、圖示設定
- 早些版本中Spring Boot對
Favicon進行了默認支持,只需要將.ico圖示檔案放在四個靜態資源目錄任意一個即可,并需要在application.properties中通過如下配置關閉默認的圖示即可
spring.mvc.favicon.enabled=false #關閉
-
但在Spring Boot專案的issues中提出,如果提供默認的Favicon可能會導致網站資訊泄露,如果用戶不進行自定義的Favicon的設定,而Spring Boot專案會提供默認的上圖圖示,那么勢必會導致泄露網站的開發框架,
-
因此,在Spring Boot2.2.x中,將默認的favicon.ico移除,同時也不再提供上述application.properties中的屬性配置

在這以后,我們需要在
index.html首頁檔案中進行配置
- 將
.ico圖片放在 resources 檔案夾下的 static 檔案夾下

- 在首頁 index.html 中引入圖片
<link rel="icon" href="/favicon.ico">
-
訪問測驗即可

注:可能會出現測驗不成功的情況,建議清除瀏覽器快取再重繪
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/120476.html
標籤:其他
