thymeleaf教程

目錄

thymeleaf的定義
spring boot整合
thymeleaf語法參考文檔
thymeleaf筆記

thymeleaf比jsp好在哪
thymeleaf簡(jiǎn)單文件
thymeleaf配置 application.properties
thymeleaf url
thymeleaf表達(dá)式
themeleaf包含 footer
themeleaf條件 if
themeleaf 遍歷
thymeleaf內(nèi)置工具
thymeleaf分頁

thymeleaf的定義

Thymeleaf是一種用于Web和獨(dú)立環(huán)境的現(xiàn)代服務(wù)器端的Java模板引擎。主要目標(biāo)是將優(yōu)雅的自然模板帶到開發(fā)工作流程中,并將HTML在瀏覽器中正確顯示,并且可以作為靜態(tài)原型,讓開發(fā)團(tuán)隊(duì)能更容易地協(xié)作。Thymeleaf使用Spring框架的模塊,與許多常見的工具集成在一起,并且可以插入自己的功能,能夠處理HTML,XML,JavaScript,CSS,TEXT,RAW六種模板模式。

spring boot整合

  1. 新建spring boot的web項(xiàng)目
    添加依賴
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>

在spring boot是1.5.X時(shí),thymeleaf依賴要用1.5.x版本,親測(cè)用2版本會(huì)找不到網(wǎng)頁。

  1. 將html網(wǎng)頁放在templates文件夾下。
  2. controller即可跳轉(zhuǎn)到html頁面,頁面路徑為以templates為基礎(chǔ)的相對(duì)路徑。

thymeleaf語法參考文檔

官方文檔:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
目前網(wǎng)上教程不太多,https://www.yiibai.com/thymeleaf/standardurlsyntax.html 重點(diǎn)看標(biāo)準(zhǔn)方言。
目前比較淺顯易懂的 http://how2j.cn/k/springboot/springboot-thymeleat/1735.html

thymeleaf筆記

thymeleaf比jsp好在哪

jsp要在服務(wù)器啟動(dòng)后轉(zhuǎn)化為html頁面。不啟動(dòng)服務(wù)器無法運(yùn)行出結(jié)果。
thymeleaf服務(wù)器不啟動(dòng)他就已經(jīng)是html。

thymeleaf簡(jiǎn)單文件

<html xmlns:th="http://www.thymeleaf.org">
<head>#內(nèi)容與html無異
<p th:text="$name">name</p>
#服務(wù)器端未啟動(dòng) 顯示name 啟動(dòng)顯示服務(wù)器端傳來的name值
#字符串拼接
<p th:text="|Hello! ${name}|"></p>

thymeleaf配置 application.properties

#thymeleaf 配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#緩存設(shè)置為false, 這樣修改之后馬上生效,便于調(diào)試
spring.thymeleaf.cache=false
#上下文 注意這里使得所有頁面網(wǎng)址前綴都變?yōu)橄率龅刂?server.context-path=/thymeleaf

thymeleaf url

引入css文件

<link rel="stylesheet" type="text/css" media="all" href="../webapp/static/css/style.css" th:href="@{/static/css/style.css}"/>

引入js文件

<script type="text/javascript" src="../webapp/static/js/thymeleaf.js" th:src="@{/static/js/thymeleaf.js}"></script>

啟動(dòng)服務(wù)器后 th:src會(huì)代替src th:href會(huì)代替href

thymeleaf表達(dá)式

controller中添加屬性

String htmlContent = "<p style='color:red'> 紅色文字</p>";
m.addAttribute("htmlContent", htmlContent);
Product currentProduct =new Product(5,"product e", 200);
m.addAttribute("currentProduct", currentProduct);

轉(zhuǎn)義與非轉(zhuǎn)義

<p th:text="${htmlContent}" ></p>
<p th:utext="${htmlContent}" ></p>

效果


image.png

獲取對(duì)象

方式1
<p th:text="${currentProduct}" ></p>
<p th:text="${currentProduct.name}" ></p>
<p th:text="${currentProduct.getName()}" ></p>
方式2
<div class="showing" th:object="${currentProduct}">
<h2>*{}方式顯示屬性</h2>
<p th:text="*{name}" ></p>
</div>

效果


image.png

此外還有算數(shù)運(yùn)算

<p th:text="${currentProduct.price+999}" ></p>

themeleaf包含 footer

<html xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="footer1"> 
   <p >All Rights Reserved</p>
</footer>
<footer th:fragment="footer2(start,now)"> 
   <p th:text="|${start} - ${now} All Rights Reserved|"></p>
</footer>
</html>

使用時(shí)按照

<div th:replace="include::footer1" ></div>
<div th:replace="include::footer2(2015,2018)" ></div>

themeleaf條件if

<p th:if="${testBoolean}" >如果testBoolean 是 true ,本句話就會(huì)顯示</p>
<p th:if="${not testBoolean}" >取反 ,所以如果testBoolean 是 true ,本句話就不會(huì)顯示</p>
<p th:text="${testBoolean}?'當(dāng)testBoolean為真的時(shí)候,顯示本句話,這是用三相表達(dá)式做的':''" ></p>

不只是布爾值的 true 和 false, th:if 表達(dá)式返回其他值時(shí)也會(huì)被認(rèn)為是 true 或 false,規(guī)則如下:

boolean 類型并且值是 true, 返回 true
數(shù)值類型并且值不是 0, 返回 true
字符類型(Char)并且值不是 0, 返回 true
String 類型并且值不是 "false", "off", "no", 返回 true
不是 boolean, 數(shù)值, 字符, String 的其他類型, 返回 true
值是 null, 返回 false

themeleaf 遍歷

controller中

 List<Product> ps = new ArrayList<>();
        ps.add(new Product(1,"product a", 50));
        ps.add(new Product(2,"product b", 100));
        ps.add(new Product(3,"product c", 150));   
        m.addAttribute("ps", ps);

html中

 <table>
        <thead>
            <tr>
                <th>id</th>
                <th>產(chǎn)品名稱</th>
                <th>價(jià)格</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="p: ${ps}">
                <td th:text="${p.id}"></td>
                <td th:text="${p.name}"></td>
                <td th:text="${p.price}"></td>
            </tr>
        </tbody>
    </table>

select與thymeleaf遍歷結(jié)合

<div class="showing">
    <h2>遍歷 select </h2>
    <select size="3">
        <option th:each="p:${ps}" th:value="${p.id}"     th:selected="${p.id==currentProduct.id}"    th:text="${p.name}" ></option>
    </select>
</div>
image.png

thymeleaf內(nèi)置工具

#dates工具
now變量是controller中聲明的Date now = new Date();

<div class="showing date">
    <h2>格式化日期</h2>
    直接輸出日期 ${now}:
    <p th:text="${now}"></p>
    默認(rèn)格式化 ${#dates.format(now)}:
    <p th:text="${#dates.format(now)}"></p>
    自定義格式化 ${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}:
    <p th:text="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"></p>
</div>
image.png

其他工具如

Execution Info
Messages
URIs/URLs
Conversions
Dates
Calendars
Numbers
Strings
Objects
Booleans
Arrays
Lists
Sets
Maps
Aggregates
IDs

手冊(cè)見 http://how2j.cn/k/springboot/springboot-tool/1741.html#nowhere

thymeleaf分頁

與數(shù)據(jù)庫連接時(shí)的分頁
pom加入

<!-- pageHelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>

controller中示例

 @RequestMapping("/listCategory")
    public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
        PageHelper.startPage(start,size,"id desc");
        List<Category> cs=categoryMapper.findAll();
        PageInfo<Category> page = new PageInfo<>(cs);
        m.addAttribute("page", page);       
        return "listCategory";
    }

配置PageHelper

package com.how2java.springboot.config; 
import java.util.Properties; 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;  
import com.github.pagehelper.PageHelper;  
@Configuration
public class PageHelperConfig {
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }
}

html頁面

 <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>編輯</td>
            <td>刪除</td>
        </tr>
        <tr th:each="c:${page.list}">
            <td th:text="${c.id}"></td>
            <td th:text="${c.name}"></td>
            <td><a th:href="@{/editCategory(id=${c.id})}">編輯</a></td>
            <td><a th:href="@{/deleteCategory(id=${c.id})}">刪除</a></td>
        </tr>
    </table>
    <br/>
    <div>
            <a th:href="@{/listCategory(start=0)}">[首  頁]</a>
            <a th:href="@{/listCategory(start=${page.pageNum-1})}">[上一頁]</a>
            <a th:href="@{/listCategory(start=${page.pageNum+1})}">[下一頁]</a>
            <a th:href="@{/listCategory(start=${page.pages})}">[末  頁]</a>
    </div>

效果


image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容