Springboot詳解如何整合使用Thymeleaf
模板引擎的作用就是我們來寫一個頁面模板,比如有些值呢,是動態(tài)的,我們寫一些表達式。而這些值,從哪來呢,就是我們在后臺封裝一些數(shù)據(jù)。然后把這個模板和這個數(shù)據(jù)交給我們模板引擎,模板引擎按照我們這個數(shù)據(jù)幫你把這表達式解析、填充到我們指定的位置,然后把這個數(shù)據(jù)最終生成一個我們想要的內容給我們寫出去,這就是我們這個模板引擎
如果我們沒有模板引擎的話,在頁面中會提示500
引入Thymeleaf
在項目中加入依賴
<!--thymeleaf--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
Thymeleaf 官網(wǎng):https://www.thymeleaf.org/
Thymeleaf 在Github 的主頁:https://github.com/thymeleaf/thymeleaf
Spring官方文檔:找到我們對應的版本
https://docs.spring.io/spring-boot/docs/2.3.7.RELEASE/reference/htmlsingle/#using-boot-starter
我們可以有通過上述的頁面找到我們需要的依賴,進而復制粘貼即可。
引入之后我們再次運行。nice
注意: 使用Thymeleaf,只需要導入對應的依賴即可。同時我們的html頁面試放在我們的templates目錄下的。
至于為什么,我們看源碼,這段源碼在ThymeleafProperties
下。
private String prefix = "classpath:/templates/"; private String suffix = ".html";
取值
那么我們應該怎么取值呢
首先在controller下編寫代碼
@Controller public class HelloController { @RequestMapping("/test") public String hello(Model model){ model.addAttribute("msg","王木木"); return "test"; } }
接下來我們在html頁面中編寫
因為我們要使用thymeleaf,需要在html文件中導入命名空間的約束。
<html lang="en" xmlns:th="http://www/thymeleaf.org">
<!DOCTYPE html> <html lang="en" xmlns:th="http://www/thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:text="${msg}"></div> </body> </html>
成功運行后
這里需要這個的th標簽。所有的html元素都科一被thymeleaf替換接管,格式為th:元素名
有無轉義
從controller傳一段信息
model.addAttribute("msg","<h1>王木木</h1>");
html中使用轉義和不轉義的情況
<div th:text="${msg}"></div> <div th:utext="${msg}"></div>
運行結果
循環(huán)
同樣在controller里傳一段信息
model.addAttribute("users", Arrays.asList("wangmumu","王木木"));
接下來在html中進行取值
<h2 th:each="user:${users}" th:text="${user}"></h2>
運行結果
到此這篇關于Springboot詳解如何整合使用Thymeleaf的文章就介紹到這了,更多相關Springboot Thymeleaf內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- springboot+thymeleaf整合阿里云OOS對象存儲圖片的實現(xiàn)
- springboot整合shiro之thymeleaf使用shiro標簽的方法
- SpringBoot整合thymeleaf 報錯的解決方案
- SpringBoot使用thymeleaf實現(xiàn)一個前端表格方法詳解
- Springboot使用thymeleaf動態(tài)模板實現(xiàn)刷新
- 淺析SpringBoot中使用thymeleaf找不到.HTML文件的原因
- springboot如何使用thymeleaf模板訪問html頁面
- springboot中thymeleaf模板使用詳解
- SpringBoot?整合Thymeleaf教程及使用方法
相關文章
SpringBoot中的RestTemplate使用方法詳解
這篇文章主要介紹了SpringBoot中的RestTemplate使用方法詳解,為了方便使用,這里我封裝成一個工具類來靜態(tài)調用RestTemplate,基于SpringBoot2.4.2版本,需要的朋友可以參考下2024-01-01動態(tài)修改spring?aop?切面信息提升自動日志輸出框架效率
這篇文章主要為大家介紹了動態(tài)修改spring?aop切面信息提升自動日志輸出框架效率,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07Java Apollo環(huán)境搭建以及集成SpringBoot案例詳解
這篇文章主要介紹了Java Apollo環(huán)境搭建以及集成SpringBoot案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-08-08IDEA 配合 Dockerfile 部署 SpringBoot 工程的注意事項
這篇文章主要介紹了IDEA 配合 Dockerfile 部署 SpringBoot 工程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09