1.springBoot引入thymleaf引擎模板
首先看一下整個項目的最終的結構
在pom.xml文件中引入thymeleaf依賴即可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
下面需要在resources目錄下創建templates目錄,並在該目錄下寫html文件,這個模板就會起作用。
因爲在springBoot默認配置中默認尋找templates文件夾下的html文件,下面在Controller文件下寫一個Controller類進行測試。
@Controller
public class HelloController {
//訪問localhost:8080/hello,返回字符串
@ResponseBody
@RequestMapping("/hello")
public String Hello(){
return "Hello World";
}
//訪問localhost:8080/index,會返回templates/projectTemplates/下的index.html文件
@RequestMapping("/index")
public String Index(){
return "projectTemplates/index";
}
}
index.html如下:其中xmlns:th="http://www.thymeleaf.org"爲命名空間,作用主要是提示thymeleaf語法。
<!DOCTYPE html>
<!--xmlns:th="http://www.thymeleaf.org"作用主要是提示thymeleaf語法-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
<script src="../projectResources/js/first.js" type="text/javascript"></script>
<link rel="stylesheet" href="../projectResources/css/first.css" type="text/css"/>
</head>
<body>
<h1>歡迎頁面</h1>
<div id = "firstImage"></div>
</body>
</html>
最終結果如下:
2.springBoot對靜態資源的映射規則
訪問當前項目的任何資源,都會找相應的靜態資源文件夾映射,對應的靜態文件夾一般創建在resources目錄下。
1)第一個靜態文件夾:/META-INF/resources
2)第二個靜態文件夾:/public
3)第三個靜態文件夾:/static
4)第四個靜態文件夾:/resources
當我們使用localhost:8080/xxx時,springBoot項目會去上述四個靜態文件夾找,如果沒有,則會報錯。假如我們在/static下又創建一個文件夾,例如:/static/images/1.png。則我們使用localhost:8080/images/1.png就可以訪問。例如圖1的目錄結構圖:在4個靜態文件下均寫了4個文件進行測試。
測試1:
測試2:
測試3:
測試4:
上述測試可以看出,項目會直接訪問靜態文件夾下的文件。
3.注意事項
對於SpringBoot,上述四個靜態文件夾和templates文件夾之間是透明的,什麼意思呢?
對於index.html文件去引用css文件,則需要"…/projectResources/css/first.css",
而不是"…/…/static/projectResources/css/first.css"。相當於/META-INF/resources、/public、/static、/resources和/templates平級且每個文件夾的文件訪問沒有任何障礙。這一點在寫WEB項目時,靜態資源之間的引用可以體現出來。