Thymeleaf【快速入門】

我沒有三顆心臟發表於2019-01-02

Thymeleaf【快速入門】

前言:突然發現自己給自己埋了一個大坑,畢設好難..每一個小點拎出來都能當一個小題目(手動擺手..),沒辦法自己選的含著淚也要把坑填完..先一點一點把需要補充的知識學完吧..

Thymeleaf介紹

稍微摘一摘【官網】上面的介紹吧(翻譯是找到,有些增加的內容):

  • 1.Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
    Thymeleaf是⾯向Web和獨⽴環境的現代伺服器端Java模板引擎,能夠處理HTML,XML,JavaScript,CSS甚⾄純⽂本。

  • 2.Thymeleaf`s main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.
    Thymeleaf旨在提供⼀個優雅的、⾼度可維護的建立模板的⽅式。 為了實現這⼀⽬標,Thymeleaf建⽴在⾃然模板的概念上,將其邏輯注⼊到模板⽂件中,不會影響模板設計原型。 這改善了設計的溝通,彌合了設計和開發團隊之間的差距。

  • 3.With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.
    對於Spring框架模組,一個允許你整合你最喜歡的工具的平臺,並且能夠插入自己的功能,Thymeleaf是理想的現代JVM HTML5 web開發工具,雖然它可以做得多。

然後官網還給出了一段看起來仍然像HTML一樣工作的整合了Thymeleaf模版的程式碼,我們大致的來感受一下:

Thymeleaf官網給的例子

簡單說, Thymeleaf 是一個跟 Velocity、FreeMarker 類似的模板引擎,它可以完全替代 JSP。

Thymeleaf與JSP的區別在於,不執行專案之前,Thymeleaf也是純HTML(不需要服務端的支援)而JSP需要進行一定的轉換,這樣就方便前端人員進行獨立的設計、除錯。相較與其他的模板引擎,它有如下三個極吸引人的特點:

  • 1.Thymeleaf 在有網路和無網路的環境下皆可執行,即它可以讓美工在瀏覽器檢視頁面的靜態效果,也可以讓程式設計師在伺服器檢視帶資料的動態頁面效果。這是由於它支援 html 原型,然後在 html 標籤裡增加額外的屬性來達到模板+資料的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 thymeleaf 的模板可以靜態地執行;當有資料返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。

  • 2.Thymeleaf 開箱即用的特性。它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表示式效果,避免每天套模板、該jstl、改標籤的困擾。同時開發人員也可以擴充套件和建立自定義的方言。

  • 3.Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美整合的可選模組,可以快速的實現表單繫結、屬性編輯器、國際化等功能。

摘自:spring boot(四):thymeleaf使用詳解-純潔的微笑

00#先把需要環境搭起來

也就是SpringBoot專案的搭建,很常規,快速搭起來:

Thymeleaf【快速入門】

稍微改改包名還有描述,點選【Next】:

Thymeleaf【快速入門】

勾選上Web/Thymeleaf支援,然後點選【Next】:

Thymeleaf【快速入門】

選擇專案儲存位置,點選【Finish】:

Thymeleaf【快速入門】

至此就簡單建立了一個用於學習Thymeleaf的簡單環境。

01#建立一個Hello Thymeleaf頁面

第一步:新建一個HelloController

在【com.wmyskxz.demo】下新建一個【controller】包,然後新建一個【HelloController】:

package com.wmyskxz.demo.controoler;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("name", "thymeleaf");
        return "hello";
    }
}

第二步:新建一個hello.html頁面

在【resources】下的【templates】下新建一個【hello.html】檔案,使用這個目錄的原因是當你使用模板引擎時Spring Boot會預設在src/main/resources/templates下去找,當然你也可以修改這個預設路徑,這裡就不做演示了:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Thymeleaf快速入門-Hello Thymeleaf</title>
</head>
<body>
<p th:text="${name}">name</p>
<p th:text="`Hello! ` + ${name} + `!`">hello world</p>
<p th:text="|Hello! ${name}!|">hello world</p>
</body>
</html>

第三步:把專案跑起來

事實上,上面已經展示了三種拼接字串的方式,你應該也能看出thymeleaf的一點端倪,不過你第一件注意到的事應該是這是一個HTML5檔案,可以由任何瀏覽器正確的顯示,因為它不包含任何非HTML得標籤(瀏覽器會忽略他們不明白的所有屬性,如:th:text

直接開啟hello.html顯示的內容

專案執行之後,我們在位址列輸入localhost:8080/hello,就會看到意料之中結果正確的頁面:

Thymeleaf【快速入門】

但是你也可能會注意到,這個模板並不是一個真正有效的HTML5文件,因為HTML5規範不允許在th:*形式中使用這些非標準屬性。事實上,我們甚至在我們的<html>標籤中新增了一個xmlns:th屬性,這絕對是非HTML5標準:<html xmlns:th="http://www.thymeleaf.org">

不管怎樣,你已經看到了我們將如何使用Thymeleaf模板引擎訪問model中的資料:“${}”,這和JSP極為相似,下面我們將進一步展示Thymeleaf的用法。

第四步:對專案做一些修改以方便除錯

現在我們基礎的環境和第一個任務(一個Hello World)頁面都已經開發完成了,但是有一點不好的是,每一次我們對頁面的修改都不能得到及時的反應,我們需要不斷的重啟伺服器以看到效果,這在實際開發過程中是十分糟糕的表現,我們需要做一些修改,讓Thymeleaf頁面能夠實時的重新整理而不需要重啟伺服器。

開啟IDEA->Setting,將下面的選項【Build project automatically】給勾選上:

Thymeleaf【快速入門】

然後按下快捷鍵【Ctrl + Alt + Shift + /】,召喚出【Maintenance】選單,進入【Registry】:

Thymeleaf【快速入門】

把【compiler.automake.allow.when.app.running】這個選項的 √ 給打上:

Thymeleaf【快速入門】

然後再把【application.properties】弄成這個樣子:

#thymeleaf 配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#快取設定為false, 這樣修改之後馬上生效,便於除錯
spring.thymeleaf.cache=false

然後重啟專案,對我們的hello.html稍稍做一些修改,稍等一會兒,你就能重新整理頁面看到效果,完美。

10#更多Thymeleaf的基礎用法

1. model 中的資料迭代

Thymeleaf 的迭代和 JSP 的寫法也很相似,我們將就上面的hello專案改一下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Thymeleaf快速入門-Hello Thymeleaf</title>
</head>
<body>
<table>
    <thead>
    <tr>
        <th>學生id</th>
        <th>學生姓名</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="s:${students}">
        <td th:text="${s.id}"></td>
        <td th:text="${s.name}"></td>
    </tr>
    </tbody>
</table>
</body>
</html>

為了配合演示,在【com.wmyskxz.demo】下新建一個【pojo】包,然後新建一個【Student】類:

package com.wmyskxz.demo.pojo;

public class Student {
    private String name;
    private Integer id;

    public Student(String name, Integer id) {
        this.name = name;
        this.id = id;
    }

    // getter and setter
}

再把controller改改,給前端新增幾條資料:

@RequestMapping("/hello")
public String hello(Model model) {

    List<Student> students = new ArrayList<>();
    students.add(new Student("張三", 1));
    students.add(new Student("李四", 2));
    students.add(new Student("王五", 3));
    students.add(new Student("二麻子", 4));
    students.add(new Student("三棒子", 5));

    model.addAttribute("students", students);
    return "hello";
}

重啟專案,然後在位址列輸入:localhost:8080/hello,能看到正確的顯示,完美:

Thymeleaf【快速入門】

程式碼解釋:

使用th:each來做迴圈迭代(th:each="s:${students}"),s作為迭代元素來使用,然後像上面一樣訪問迭代元素中的屬性,相信這樣的用法應該不會陌生。

進階-帶狀態的遍歷

我們也可以使用th:each="s,status:${students}"方式遍歷,就可以把狀態放在status裡面了,同時還可以用th:class="${stauts.even}?`even`:`odd`"來判斷奇偶。

status裡面包含的資訊大致如下:

屬性 說明
index 從0開始的索引值
count 從1開始的索引值
size 集合內元素的總量
current 當前的迭代物件
even/odd boolean型別的,用來判斷是偶數個還是奇數個
first boolean型別,判斷是否為第一個
last boolean型別,判斷是否為最後一個

我們再次來修改一下我們的hello.html,讓它多顯示一行index屬性,並增加一些簡單的效果好讓單雙行區別開來:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Thymeleaf快速入門-Hello Thymeleaf</title>
</head>
<body>
<table>
    <thead>
    <tr>
        <th>index</th>
        <th>學生id</th>
        <th>學生姓名</th>
    </tr>
    </thead>
    <tbody>
    <tr th:class="${status.even}?`even`:`odd`" th:each="s,status:${students}">
        <td th:text="${status.index}"></td>
        <td th:text="${s.id}"></td>
        <td th:text="${s.name}"></td>
    </tr>
    </tbody>
</table>
</body>
<style>
    .even{
        background-color: hotpink;
    }
    .odd{
        background-color: cornflowerblue;
    }
</style>
</html>

不用重啟,重新整理一下頁面就可以看到效果,完美:

Thymeleaf【快速入門】

2. 資料判斷

Thymeleaf 的條件判斷是通過th:if來做的,只有條件為真的時候才會顯示當前元素,取反可以用notth:if="not 條件")或者th:unless,或者常見的三元判斷符(x?y:z)也是適用的,我們動手再來修改我們的hello.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Thymeleaf快速入門-Hello Thymeleaf</title>
</head>
<body>
<!-- 當students集合為空則顯示提示資訊 -->
<div th:if="${#lists.isEmpty(students)}">studnets集合為空!</div>
<!-- 當students集合不為空時才會顯示下面的元素 -->
<div th:if="${not #lists.isEmpty(students)}">
    <table>
        <thead>
        <tr>
            <th>index</th>
            <th>學生id</th>
            <th>學生姓名</th>
        </tr>
        </thead>
        <tbody>
        <tr th:class="${status.even}?`even`:`odd`" th:each="s,status:${students}">
            <td th:text="${status.index}"></td>
            <td th:text="${s.id}"></td>
            <td th:text="${s.name}"></td>
        </tr>
        </tbody>
    </table>
</div>
</body>
<style>
    .even {
        background-color: hotpink;
    }

    .odd {
        background-color: cornflowerblue;
    }
</style>
</html>

然後我們相應的把Controller丟給hello.html的資料給清空:

@RequestMapping("/hello")
public String hello(Model model) {

    List<Student> students = new ArrayList<>();
//        students.add(new Student("張三", 1));
//        students.add(new Student("李四", 2));
//        students.add(new Student("王五", 3));
//        students.add(new Student("二麻子", 4));
//        students.add(new Student("三棒子", 5));

    model.addAttribute("students", students);
    return "hello";
}

重啟專案,重新整理頁面,能看到正確的錯誤提示資訊(對於這樣的,需要有錯誤提示的頁面我也不知道應該怎麼寫好,這裡就簡單示範一下,如果知道怎麼寫好的小夥伴記得提示一下啊):

Thymeleaf【快速入門】

程式碼解釋:

通過${not #lists.isEmpty(students)}表示式,判斷了students是否為空,Thymeleaf支援>、<、>=、<=、==、!=作為比較條件,同時也支援將SpringEL表示式語言用於條件中,表示式中的#lists.isEmpty()語法是Thymeleaf模板自帶的一種內建工具,像這樣的內建工具不僅方便而且能提高我們的效率,完整的內建工具在這裡可以看到:【傳送門】

3. 在 JavaScript 中訪問 model

首先我們需要學習如何在Thymeleaf中引用靜態資源,很簡單,使用@{}就可以,這在JSP下是極易出錯的。我們在【main】目錄下新建一個【webapp】目錄,然後在【staitc/js】目錄下新建一個【thymeleaf.js】檔案:

function testFunction(){
    alert("test Thymeleaf.js!");
}

在hello.html的<head>標籤中新增上下面這句話:

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

通過th:href="@{/static/js/thymeleaf.js}"這種方式,可以在渲染後的html裡自動生成上下文路徑,為了方便我們除錯,也就是能在顯示器中直接開啟html檔案進行效果的檢視,我們還新增了src屬性(src="../../webapp/static/js/thymeleaf.js"

重新整理專案,能正確得到提示資訊:

Thymeleaf【快速入門】

然後我們把hello.html改寫成下面這個樣子:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Thymeleaf快速入門-Hello Thymeleaf</title>
    <script th:inline="javascript">
        var single = [[${student}]];
        console.log(single.name + "/" + single.id);
    </script>
</head>
<body>
</body>
</html>

再讓Controller簡單的傳一個學生到前臺:

@RequestMapping("/hello")
public String hello(Model model) {
    model.addAttribute("student", new Student("我沒有三顆心臟", 1));
    return "hello";
}

重新整理專案,按下F12,就可以在控制檯中看到正確的資訊了:

Thymeleaf【快速入門】

程式碼解釋:

通過th:inline="javascript"新增到script標籤,這樣JavaScript程式碼即可訪問model中的屬性,再通過[[${}]]格式來獲得實際的值。

4. 包含

我們在開發中常常都把頁面共同的header和footer提取出來,弄成單獨的頁面,然後讓該包含的頁面包含進來,我們就拿footer舉例,首先在【templates】下新建一個要背其他頁面包含的footer頁面【include】:

<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>

然後直接在我們的hello.html頁面中分別引用上面頁面定義好的兩個foot:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Thymeleaf快速入門-Hello Thymeleaf</title>
</head>
<body>
<div th:include="include::footer1"></div>
<div th:replace="include::footer2(2015,2018)"></div>
</body>
</html>

重新整理頁面,可以看到效果:

Thymeleaf【快速入門】

程式碼解釋:

我們可以使用th:fragment屬性來定義被包含的模板片段,然後使用th:includeth:replace兩個標籤來直接引用標記好的片段,上面hello.html其實就相當於:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Thymeleaf快速入門-Hello Thymeleaf</title>
</head>
<body>
<div>
    <p>All Rights Reserved</p>
</div>
<footer>
    <p>2015 - 2018 All Rights Reserved</p>
</footer>
</body>
</html>

也可以很明顯感覺到兩個標籤的差別,include會保留自己的主標籤,而replace會保留fragment的主標籤。

11#一個CRUD+分頁的例項

接下來我們沿用上面的基礎,把這個專案進行一定的擴充套件,變成一個CRUD+分頁的完整專案,不過首先,我們需要把之前因為不好習慣寫的pojo.student類裡的id和name順序交換一下,好匹配資料庫裡的結構:

package com.wmyskxz.demo.pojo;
public class Student {
    private Integer id;
    private String name;
    // getter and setter
}

第一步:準備好資料庫環境

建表SQL:

create database wmyskxz;
use wmyskxz;
CREATE TABLE student (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(30),
  PRIMARY KEY (id)
) DEFAULT CHARSET=UTF8;

第二步:修改application.properties和pom.xml

增加資料庫相關配置到application,properties中,完整的檔案如下:

#thymeleaf 配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#快取設定為false, 這樣修改之後馬上生效,便於除錯
spring.thymeleaf.cache=false

#資料庫
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/wmyskxz?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

往pom.xml增加jdbc,mybatis,pageHelper的jar包:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wmyskxz</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot + Thymeleaf</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional> <!-- 這個需要為 true 熱部署才有效 -->
        </dependency>

        <!-- servlet依賴. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!-- tomcat的支援.-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
        <!-- pageHelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

第三步:增加StudentMapper

新建【mapper】包,並在其下新增StudentMapper介面:

package com.wmyskxz.demo.mapper;

import com.wmyskxz.demo.pojo.Student;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface StudentMapper {

    @Select("select * from student")
    List<Student> findAll();

    @Insert("insert into student ( name ) values (#{name}) ")
    int save(Student student);

    @Delete("delete from student where id= #{id} ")
    void delete(int id);

    @Select("select * from student where id= #{id} ")
    Student get(int id);

    @Update("update student set name=#{name} where id=#{id} ")
    int update(Student student);
}

第四步:新增StudentController類

在【controller】包下新增一個【StudentController】類:

package com.wmyskxz.demo.controoler;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wmyskxz.demo.mapper.StudentMapper;
import com.wmyskxz.demo.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class StudentController {
    @Autowired
    StudentMapper studentMapper;

    @RequestMapping("/addStudent")
    public String listStudent(Student student) throws Exception {
        studentMapper.save(student);
        return "redirect:listStudent";
    }

    @RequestMapping("/deleteStudent")
    public String deleteStudent(Student student) throws Exception {
        studentMapper.delete(student.getId());
        return "redirect:listStudent";
    }

    @RequestMapping("/updateStudent")
    public String updateStudent(Student student) throws Exception {
        studentMapper.update(student);
        return "redirect:listStudent";
    }

    @RequestMapping("/editStudent")
    public String listStudent(int id, Model m) throws Exception {
        Student student = studentMapper.get(id);
        m.addAttribute("student", student);
        return "editStudent";
    }

    @RequestMapping("/listStudent")
    public String listStudent(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<Student> students = studentMapper.findAll();
        PageInfo<Student> page = new PageInfo<>(students);
        m.addAttribute("page", page);
        return "listStudent";
    }
}

第五步:配置PageHelper

新建【config】包,並在下面新建【PageHelperConfig】類:

package com.wmyskxz.demo.config;

import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@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檔案

為了演示,我們簡單新增兩個頁面就好了,一個是【listStudent.html】:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf快速入門-CRUD和分頁例項</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>

<div style="width:500px;margin:20px auto;text-align: center">
    <table align=`center` border=`1` cellspacing=`0`>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>編輯</td>
            <td>刪除</td>
        </tr>
        <tr th:each="student:${page.list}">
            <td th:text="${student.id}"></td>
            <td th:text="${student.name}"></td>
            <td><a th:href="@{/editStudent(id=${student.id})}">編輯</a></td>
            <td><a th:href="@{/deleteStudent(id=${student.id})}">刪除</a></td>
        </tr>
    </table>
    <br/>
    <div>
        <a th:href="@{/listStudent(start=0)}">[首 頁]</a>
        <a th:href="@{/listStudent(start=${page.pageNum-1})}">[上一頁]</a>
        <a th:href="@{/listStudent(start=${page.pageNum+1})}">[下一頁]</a>
        <a th:href="@{/listStudent(start=${page.pages})}">[末 頁]</a>
    </div>
    <br/>
    <form action="addStudent" method="post">
        name: <input name="name"/> <br/>
        <button type="submit">提交</button>
    </form>
</div>
</body>
</html>

另一個就是編輯Student的頁面【editStudent.html】:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf快速入門-CRUD和分頁例項</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div style="margin:0px auto; width:500px">

    <form action="updateStudent" method="post">

        name: <input name="name" th:value="${student.name}"/> <br/>

        <input name="id" type="hidden" th:value="${student.id}"/>
        <button type="submit">提交</button>

    </form>
</div>
</body>

</html>

第七步:執行專案

在新增了一些資料之後,可以觀察到各項功能都是可以正常使用的,這個例子也是我直接借鑑how2j教程裡的原始碼寫的,原文在這裡:【傳送門】,執行之後,可以看到大概是這樣的效果,完美:

Thymeleaf【快速入門】


至此,我們就差不多算是對Thymeleaf入了門。

按照慣例黏一個尾巴,話說有木有懂公眾號運營的小夥伴啊?求指教!

歡迎轉載,轉載請註明出處!
簡書ID:@我沒有三顆心臟
github:wmyskxz
歡迎關注公眾微訊號:wmyskxz
分享自己的學習 & 學習資料 & 生活
想要交流的朋友也可以加qq群:3382693