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項目的搭建,很常規,快速搭起來:

稍微改改包名還有描述,點擊【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

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

項目運行之后,我們在地址欄輸入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來做的,只有條件為真的時候才會顯示當前元素,取反可以用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";
}

重啟項目,刷新頁面,能看到正確的錯誤提示信息(對於這樣的,需要有錯誤提示的頁面我也不知道應該怎么寫好,這里就簡單示范一下,如果知道怎么寫好的小伙伴記得提示一下啊):

代碼解釋:

通過${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: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入了門。

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM