天天看點

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 是一個跟 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項目的搭建,很正常,快速搭起來:

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

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

選擇項目儲存位置,點選【Finish】:

至此就簡單建立了一個用于學習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

項目運作之後,我們在位址欄輸入

localhost:8080/hello

,就會看到意料之中結果正确的頁面:

但是你也可能會注意到,這個模闆并不是一個真正有效的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】給勾選上:

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

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

然後再把【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

,能看到正确的顯示,完美:

代碼解釋:

使用

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>
           

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

2. 資料判斷

Thymeleaf 的條件判斷是通過

th:if

來做的,隻有條件為真的時候才會顯示目前元素,取反可以用

not

th: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";
}
           

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

通過

${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"

重新整理項目,能正确得到提示資訊:

然後我們把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,就可以在控制台中看到正确的資訊了:

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>
           

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

我們可以使用

th:fragment

屬性來定義被包含的模闆片段,然後使用

th:include

th: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入了門。

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

歡迎轉載,轉載請注明出處!

簡書ID:@我沒有三顆心髒

github:wmyskxz

歡迎關注公衆微信号:wmyskxz

分享自己的學習 & 學習資料 & 生活

想要交流的朋友也可以加qq群:3382693

繼續閱讀