一. 什么是Thymeleaf
Thymeleaf是面向Web和獨立環(huán)境的現(xiàn)代服務器端Java模板引擎。
Thymeleaf的主要目標是為您的開發(fā)工作流程帶來優(yōu)雅的自然模板 - 可以正確顯示在瀏覽器中的HTML,也可以作為靜態(tài)原型工作,從而在開發(fā)團隊中進行更強大的協(xié)作。
隨著Spring框架的模塊,與您最喜歡的工具的集成,以及插入自己的功能的能力,Thymeleaf是現(xiàn)代HTML5 JVM Web開發(fā)的理想選擇,盡管它可以做的更多。
好吧,我承認剛才那段是Thymeleaf官方的說明,我只不過機翻了一下。下面咱們說點人話。Thymeleaf就是jsp的高端升級版。
二. 什么情況適合使用Thymeleaf
Thymeleaf顯然是一個開發(fā)頁面的技術,現(xiàn)在各種前端技術層出不窮,比如現(xiàn)在主流的Vue、React、AngularJS等。很多人可能會要問,這個Thymeleaf相對于這些前端框架到底有啥優(yōu)勢。
其實,Thymeleaf跟那些前端框架根本不是一個類型的東西,也沒有啥可比性。
Thymeleaf和老牌的jsp屬于非前后分離的思路來開發(fā)的。后端通過數(shù)據(jù)渲染html的模板,渲染后模板就是個完整的html頁面,將頁面返回給請求方。
主流的前端框架是基于前后端分離的思路來開發(fā)的,前端頁面通過ajax來調(diào)用后端的rest接口來獲取數(shù)據(jù),再通過js進行渲染頁面(不管什么前端技術其實都是對js進行了封裝,js依然是底層核心)。
下面看下springboot配合Thymeleaf完美實現(xiàn)遍歷功能,內(nèi)容詳情如下所示:
1:控制層代碼,寫一個數(shù)組集合
2:視圖層:寫th:each這里類似于vue語法
結(jié)果展示:
源碼:控制層
package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.util.Arrays; /** * @author ${范濤之} * @Description * @create 2021-09-11 20:31 * 自動裝配 * 本身就是spring的組件 */ @Controller public class HelloController { @GetMapping("/test") public String test(Model model){ model.addAttribute("msg","<h1>helloftzdsj</h1>"); model.addAttribute("users", Arrays.asList("fantaozhi","dengsijia")); return "index"; } }
源碼:視圖層
<!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> <div th:utext="${msg}"></div> //轉(zhuǎn)意 <hr> <h3 th:each="user:${users}" th:text="${user}"></h3> </body> </html>
同樣可以在視圖層這樣寫:
使用中括號(但是不建議)
<h3 th:each="user:${users}"> [[${user}]]</h3>
實現(xiàn)了同樣的效果
到此這篇關于springboot配合Thymeleaf完美實現(xiàn)遍歷的文章就介紹到這了,更多相關springboot Thymeleaf遍歷內(nèi)容請搜索服務器之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/justleavel/article/details/120307306