Spring Boot2 實戰系列之使用Thymeleaf模板引擎

前言

Thymeleaf 是一個 xml, xhtml,html5 的模板引擎,Spring Boot 官方推薦使用 Thymeleaf 引擎,因爲它對 Spring MVC 提供了完美的支持。我們知道以前的 Spring MVC web應用在視圖層常使用 JSP,但 springboot 使用的是內嵌的 servlet 容器,而內嵌的 Tomcat 和 Jetty 不支持以 jar 形式運行 JPS,Undertow也不支持 JPS,所以在SpringBoot 中我們可以使用 Thymeleaf來代替 JSP。

在 Spring Boot 中使用 Thymeleaf 非常方便,它已經通過 org.springframework.boot.autoconfigure.thymeleaf 包對 Thymeleaf 進行了自動配置, 如下圖所示
在這裏插入圖片描述

我們只需要引入它的依賴即可

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

下面通過一個例子來說明 Thymeleaf 的一些用法,更多詳情請看 Thymeleaf 官網:https://www.thymeleaf.org/

創建項目

項目結構圖如下:

在這裏插入圖片描述

pom 依賴文件如下:

<?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 https://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.2.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>top.yekongle</groupId>
	<artifactId>springboot-thymeleaf-sample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-thymeleaf-sample</name>
	<description>Thymeleaf sample for Spring Boot</description>

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

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

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

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

</project>

代碼編寫

application.properties, 全局配置文件

# Thymeleaf 配置
# 模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
# 文件後綴
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
# 編碼
spring.thymeleaf.encoding=UTF-8
# 關閉緩存
spring.thymeleaf.cache=false

Product.java, 商品屬性

package top.yekongle.thymeleaf.entity;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class Product {
    private String category;
    private String name;
    private double price;
}

PageController.java, 將商品信息返回給頁面

package top.yekongle.thymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import top.yekongle.thymeleaf.entity.Product;

import java.util.ArrayList;
import java.util.List;

@Controller
public class PageController {

    @GetMapping
    public String index(Model model) {
        List<Product> productList = this.getProductList();
        model.addAttribute("products", productList);
        model.addAttribute("title", "商品列表");
        return "index";
    }

    List<Product> getProductList() {
        List<Product> productList = new ArrayList<>();
        Product product1 = new Product("手機", "小米10", 3499);
        Product product2 = new Product("手機", "華爲P40", 4188);
        Product product3 = new Product("手機", "一加8", 3999);
        productList.add(product1);
        productList.add(product2);
        productList.add(product3);

        return productList;
    }
}

index.html,商品展示頁面

<html xmlns:th="http://www.thymeleaf.org"><!-- Thymeleaf的命名空間,將靜態頁面轉換爲動態的視圖 -->
<head>
    <meta content="text/html;charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link th:href="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet"/>
</head>
<body>

<div class="container">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <!-- 需要動態處理的元素使用 th: 爲前綴,通過 ${} 訪問 model中的屬性-->
            <h3 class="panel-title" th:text="${title}">title</h3>
        </div>
        <div class="panel-body">
            <!--數據判斷-->
            <div th:if="${not #lists.isEmpty(products)}">
                <table class="table table-bordered table-hover">
                    <thead>
                    <tr>
                        <th>Category</th>
                        <th>Name</th>
                        <th>Price</th>
                    </tr>
                    </thead>
                    <tbody>
                        <!--數據迭代-->
                        <tr th:each="product: ${products}">
                            <td th:texts="${product.category}">Category</td>
                            <td th:text="${product.name}">name</td>
                            <td th:text="${#numbers.formatDecimal(product.price, 1, 2)}">0.99</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>


<script th:src="@{jquery.min.js}" type="text/javascript"></script>s
<script th:src="@{bootstrap/js/bootstrap.min.js}"></script>

<!-- 在 javascript 中訪問model屬性 -->
<script th:inline="javascript">
  	var title = [[${title}]];
  	console.log(title);
</script>

</body>
</html>

運行演示

啓動項目
訪問 http://localhost:8080/, 商品信息都展示了出來,控制檯也打印出了屬性 title

在這裏插入圖片描述

項目已上傳至 Github: https://github.com/yekongle/springboot-code-samples/tree/master/springboot-thymeleaf-sample , 希望對小夥伴們有幫助哦。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章