Thymeleaf是什麼?
簡單說, Thymeleaf 是一個跟 Velocity、FreeMarker 類似的模板引擎,它可以完全替代 JSP 。
特點:
1.Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由於它支持 html 原型,然後在 html 標籤裏增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。
2.Thymeleaf 開箱即用的特性。它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表達式效果,避免每天套模板、該jstl、改標籤的困擾。同時開發人員也可以擴展和創建自定義的方言。
3. Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。
集成Thymeleaf
1.引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.生成配置文件
- 新建一個一個Source Folder ,目錄爲src/main/resources。
- 創建靜態資源文件夾static,引入jquery、bootstrap等靜態資源
SpringBoot會默認找一個叫application.properties的文件。
添加Thymeleaf配置項
#thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
#拼接前綴與後綴,去創建templates目錄,裏面放置模板文件
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
在resources目錄下新建templates。新建hello.html頁面
<!DOCTYPE html>
<!-- 使用thymeleaf,配置相應的 -->
<html xmlns:th="http://www.thymeleaf.org"> <!-- th!!! 命名空間使用 -->
<head>
<meta charset="UTF-8"/><!--<meta charset="UTF-8" /> thymeleaf模板引擎默認是Template modes:HTML5解析的,所以解析比較嚴格。 -->
<title>AA</title>
</head>
<body>
<p th:text="'hello1:'+${name}"></p>
</body>
</html>
Controller裏面進行測試。
//@responseBody註解的作用是將controller的方法返回的對象通過適當的轉換器轉換爲指定的格式之後,寫入到response對象的body區,通常用來返回JSON數據或者是XML
//數據,需要注意的呢,在使用此註解之後不會再走視圖處理器,而是直接將數據寫入到輸入流中,他的效果等同於通過response對象輸出指定格式的數據。
@RequestMapping("/thymeleaf") //用thymeleaf返回模板,用String返回!!!
//@ResponseBody
//@responsebody表示該方法的返回結果直接寫入HTTP response body中。
public String helloThymeleaf(Model model) {//0代表成功
model.addAttribute("name", "pitt");
return "hello";//他會從配置文件裏面去找
}
注意:取消@ResponseBody註解!