SpringBoot中使用Thymeleaf模板詳情
一.什么是Thymeleaf
官網(wǎng)原話:Thymeleaf是適用于Web和獨立環(huán)境的現(xiàn)代服務(wù)器端Java模板引擎,能夠處理HTML,XML,JavaScript,CSS甚至純文本。 Thymeleaf的主要目標是提供一種優(yōu)雅且高度可維護的模板創(chuàng)建方式。為此,它以自然模板的概念為基礎(chǔ),以不影響模板用作設(shè)計原型的方式將其邏輯注入模板文件。這樣可以改善設(shè)計溝通,并縮小設(shè)計團隊與開發(fā)團隊之間的差距。Thymeleaf是一個HTML5模板引擎,可用于Web環(huán)境中的應(yīng)用開發(fā)。Thymeleaf提供了一個用于整合Spring MVC的可選模塊,在應(yīng)用開發(fā)中,你可以使用Thymeleaf來完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目標在于提供一種可被瀏覽器正確顯示的、格式良好的模板創(chuàng)建方式。thymeleaf模板引擎,替代jsp。
二.SpringBoot中使用Thymeleaf模板
1.pom.xml中添加thymeleaf依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.關(guān)閉thymeleaf緩存
在application.yml中的spring:下添加如下代碼(能讓改動的頁面及時生效,實現(xiàn)類似熱部署效果):
#能讓改動的頁面及時生效,實現(xiàn)類似熱部署效果 thymeleaf: cache: false
注意縮進,添加后縮進如下:
3.創(chuàng)建thymeleaf模板頁面
創(chuàng)建一個普通的html文件hello.html,如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> </html>
在html的標簽上加入名稱空間xmlns:th="http://www.thymeleaf.org"
表示該頁面是一個thymeleaf模板頁面。 即把上述代碼中<html lang="en">
換成<html lang="en" xmlns:th="http://www.thymeleaf.org">
這樣就可以在頁面中的標簽內(nèi)使用th屬性取出model中的值,類似于EL表達式。 具體用法代碼如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p th:text="'歡迎來到中國,我叫'+${name}+',今年'+${age}+'歲。'"></p> <p>歡迎來到中國,我叫<span th:text="${name}"></span>,今年<span th:text="${age}"></span>歲。</p> </body> </html>
4.創(chuàng)建一個類(用于與上述html頁面交互)
ackage com.ysw.springboot01.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/thy") public class ThymeleafController { @RequestMapping("/hello") public String hello0(Model model){ //向model中存入數(shù)據(jù) model.addAttribute("name","李白"); model.addAttribute("age","18"); //跳轉(zhuǎn)到hello.html模版引擎 return "hello"; } }
5.訪問服務(wù)路徑
效果如下:
到此這篇關(guān)于SpringBoot中使用Thymeleaf模板詳情的文章就介紹到這了,更多相關(guān)SpringBoot使用Thymeleaf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SWT(JFace) Wizard(Eclipse插件編程必備)
SWT(JFace)小制作:Wizard(Eclipse插件編程必備)2009-06-06在Spring中利用@Order注解對bean和依賴進行排序
在Spring框架中,@Order是一個經(jīng)常被忽視但非常重要的注解,在項目開發(fā)中,當我們需要維護bean的特定順序或者存在許多相同類型的bean時,這個注解就發(fā)揮了作用,這篇文章講的就是如何利用@Order注解對bean和依賴進行排序,需要的朋友可以參考下2023-11-11使用Java實現(xiàn)簡單搭建內(nèi)網(wǎng)穿透
內(nèi)網(wǎng)穿透是一種網(wǎng)絡(luò)技術(shù),適用于需要遠程訪問本地部署服務(wù)的場景,本文主要為大家介紹了如何使用Java實現(xiàn)簡單搭建內(nèi)網(wǎng)穿透,感興趣的可以了解下2024-02-02