前情提要
使用過vue.js的人都知道它的數據綁定是多麼的方便,其實通過純js,我們也可以實現這種操作,通過Ajax異步獲取數據並放入相應的元素中,而在SpringBoot中,也同樣提供了數據綁定的實現,通過使用thymleaf模板,可以實現類似於vue.js那樣的數據綁定,只需要訪問一個url,就能動態獲取裏面的所有數據
SpringBoot使用thymleaf模板的簡單實例
首先,我們需要引入thymleaf模板的依賴,SpringBoot默認使用的就是thymleaf,所以我們在pom.xml中引入如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
然後創建一個Controller類,這裏需要注意的是:Controller類的修飾註解不是@RestController,而是@Controller,他們的區別可以去百度:
package org.framework.demo.section1;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
/**
* 使用模板
* @author chengxi
*/
@Controller
public class TemplateController {
@RequestMapping("/temp")
public String gettemp(Map<String,String> map){
map.put("info","hello thymeleaf");
return "/temp1";
}
}
接下來就需要創建模板文件了,上面的請求對應的模板文件就是classpath: templates/temp1.html,默認是html文件,然後我們在resources目錄下面創建templates文件夾,該文件夾是SprignBoot模板文件默認的目錄,在該目錄下面創建temp1.html,如果想要使用請求處理方法中map注入的info可以在temp1.html文件中寫入如下代碼:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<title>Hello HTML</title>
</head>
<body>
<h1 th:text="${info}"></h1>
</body>
</html>
在html中thymleaf模板的使用類似於vue.js
接下來,啓動tomcat測試類,輸入網址:localhost:8080/temp
就會看到輸出的頁面是我們編寫的temp1.html文件
thymleaf模板文件中引入外部文件
在thymleaf模板中引入外部的js/css/img文件時,對應的文件是放在classpath: static目錄下面的,因此我們使用外部的js、css、img文件時需要創建與templates同級的static並放到這裏面,目錄使用的方式爲:/js/index.js
格式,具體可以參考優秀博客:springBoot項目中使用了thymeleaf模板,怎麼在html文件中調用外部的.js文件
thymleaf模板文件的實時編輯
在使用thymleaf模板的時候,我們會發現一個問題,就是我們引入了html文件之後,在不重啓項目的情況下改變html文件,然後保存,刷新頁面,效果仍然沒變,這是因爲thmyleaf的緩存導致的,要想實時改變,就需要關閉thymleaf的緩存,關閉的方式很簡單,在application.properties屬性配置文件中添加如下一行代碼:
spring.thymleaf.cache = false
這樣一來,就能關閉thymleaf的緩存,從而實現實時編輯html文件了