SpringBoot(四):Spring Boot 整合 Thymeleaf

1 Thymeleaf简介

Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点

1.Thymeleaf 在有网络和无网络的环境下皆可运行

它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板 + 数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

2.Thymeleaf 开箱即用的特性。

它提供标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式效果,避免每天套模板、改 JSTL、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

3.Thymeleaf 提供 Spring 标准方言和一个与 SpringMVC 完美集成的可选模块

可以快速的实现表单绑定、属性编辑器、国际化等功能。

2 为什么使用Thymeleaf

如果希望以 Jar 形式发布模块则尽量不要使用 JSP 相关知识,这是因为 JSP 在内嵌的 Servlet 容器上运行有一些问题 (内嵌 Tomcat、 Jetty 不支持 Jar 形式运行 JSP,Undertow 不支持 JSP)。

Spring Boot 中推荐使用 Thymeleaf 作为模板引擎,因为 Thymeleaf 提供了完美的 Spring MVC 支持
Spring Boot 提供了大量模板引擎,包括:

  1. FreeMarker 老的模版引擎
  2. Groovy
  3. Mustache
  4. Thymeleaf 官方推荐
  5. Velocity
  6. Beetl 号称比Thymeleaf快10倍

3 第一个 Thymeleaf 模板页

3.1 引入依赖

主要增加 spring-boot-starter-thymeleafnekohtml 这两个依赖

spring-boot-starter-thymeleaf:Thymeleaf 自动配置
nekohtml:允许使用非严格的 HTML 语法
完整的 pom.xml 如下:

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

    <groupId>com.funtl</groupId>
    <artifactId>hello-spring-boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>hello-spring-boot</name>
    <description></description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <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-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.funtl.hello.spring.boot.HelloSpringBootApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3.2在 application.yml 中配置 Thymeleaf

spring:
  thymeleaf:
    cache: false # 开发时关闭缓存,不然没法看到实时页面
    mode: LEGACYHTML5 # 用非严格的 HTML
    encoding: UTF-8
    servlet:
      content-type: text/html

3.3 创建测试用 JavaBean

创建一个测试效果的 JavaBean,简单封装一下即可

package com.funtl.hello.spring.boot.entity;

import java.io.Serializable;

public class PersonBean implements Serializable {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

3.4 创建测试用 Controller

创建一个 Controller,造一些测试数据并设置跳转

package com.funtl.hello.spring.boot.controller;

import com.funtl.hello.spring.boot.entity.PersonBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

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

@Controller
@RequestMapping(value = "thymeleaf")
public class IndexController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {
        PersonBean person = new PersonBean();
        person.setName("张三");
        person.setAge(22);

        List<PersonBean> people = new ArrayList<>();
        PersonBean p1 = new PersonBean();
        p1.setName("李四");
        p1.setAge(23);
        people.add(p1);

        PersonBean p2 = new PersonBean();
        p2.setName("王五");
        p2.setAge(24);
        people.add(p2);

        PersonBean p3 = new PersonBean();
        p3.setName("赵六");
        p3.setAge(25);
        people.add(p3);

        model.addAttribute("person", person);
        model.addAttribute("people", people);

        return "index";
    }
}

3.5 创建测试页面

在 templates 目录下创建 index.html 文件,代码如下:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello Thymeleaf</title>
</head>
<body>
    <div>
        <span>访问 Model:</span><span th:text="${person.name}"></span>
    </div>
    <div>
        <span>访问列表</span>
        <table>
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                </tr>
            </thead>
            <tbody>
                <tr th:each="human : ${people}">
                    <td th:text="${human.name}"></td>
                    <td th:text="${human.age}"></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

修改 html 标签用于引入 thymeleaf 引擎,这样才可以在其他标签里使用 th:* 语法,声明如下:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

3.6 测试访问

启动成功后,访问:http://localhost:9090/thymeleaf/index 即可看到效果
在这里插入图片描述

4 Thymeleaf 常用语法

4.1 引入 Thymeleaf

修改 html 标签用于引入 thymeleaf 引擎,这样才可以在其他标签里使用th:*语法,这是下面语法的前提。

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

4.2 获取变量值

<p th:text="'Hello!, ' + ${name} + '!'" >name</p>

可以看出获取变量值用 $ 符号,对于javaBean的话使用 变量名.属性名 方式获取,这点和 EL 表达式一样.

另外$表达式只能写在th标签内部,不然不会生效,上面例子就是使用 th:text标签的值替换 p 标签里面的值,至于 p 里面的原有的值只是为了给前端开发时做展示用的.这样的话很好的做到了前后端分离.

4.3 引入 URL

Thymeleaf 对于 URL 的处理是通过语法@{…}来处理的

<a th:href="@{http://www.baidu.com}">绝对路径</a>
<a th:href="@{/}">相对路径</a>
<a th:href="@{css/bootstrap.min.css}">Content路径,默认访问static下的css文件夹</a>

类似的标签有:th:href 和 th:src

4.4 字符串替换

很多时候可能我们只需要对一大段文字中的某一处地方进行替换,可以通过字符串拼接操作完成:

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

一种更简洁的方式是:

<span th:text="|Welcome to our application, ${user.name}!|">

当然这种形式限制比较多,|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等。

4.5 运算符

在表达式中可以使用各类算术运算符,例如+, -, *, /, %

th:with="isEven=(${prodStat.count} % 2 == 0)"

逻辑运算符>, <, <=,>=,==,!=都可以使用,唯一需要注意的是使用<,>时需要用它的HTML转义符:

th:if="${prodStat.count} &gt; 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"

4.6 条件判断

4.6.1 if/unless

Thymeleaf 中使用 th:ifth:unless属性进行条件判断,下面的例子中,标签只有在th:if中条件成立时才显示:

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

th:unlessth:if 恰好相反,只有表达式中的条件不成立,才会显示其内容。

4.6.2 switch

Thymeleaf 同样支持多路选择 Switch 结构:

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
</div>

默认属性 default 可以用 * 表示:

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

4.6.3 循环

渲染列表数据是一种非常常见的场景,例如现在有 n 条记录需要渲染成一个表格,该数据集合必须是可以遍历的,使用 th:each 标签:

<body>
  <h1>Product list</h1>

  <table>
    <tr>
      <th>NAME</th>
      <th>PRICE</th>
      <th>IN STOCK</th>
    </tr>
    <tr th:each="prod : ${prods}">
      <td th:text="${prod.name}">Onions</td>
      <td th:text="${prod.price}">2.41</td>
      <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    </tr>
  </table>

  <p>
    <a href="../home.html" th:href="@{/}">Return to home</a>
  </p>
</body>

可以看到,需要在被循环渲染的元素(这里是)中加入 th:each 标签,其中 th:each=“prod : ${prods}” 意味着对集合变量 prods 进行遍历,循环变量是 prod 在循环体中可以通过表达式访问。

5 Thymeleaf 模板布局

这节主要介绍模板的引入。及如何在不改变前端人员的 HTML 显示结果的情况下设计模板(通过属性配置动态时不显示的部分)。

5.1 模板模块导入

首先定义一个 /resources/templates/footer.html 文件:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <body>
        <div th:fragment="copy">
            &copy; 2018 Copyright by Lusifer.
        </div>
    </body>
</html>

上面的代码定义了一个片段称为 copy,我们可以很容易地使用 th:include或者th:replace属性包含在我们的主页上

<body>
...
<div th:include="footer :: copy"></div>
</body>

include的表达式想当简洁。这里有三种写法:

  • templatename::domselector 或者 templatename::[domselector] 引入模板页面中的某个模块
  • templatename引入模板页面
  • ::domselector 或者 this::domselector 引入自身模板的模块
    上面所有的 templatename 和 domselector 的写法都支持表达式写法:
<div th:include="footer :: (${user.isAdmin}? #{footer.admin} : #{footer.normaluser})"></div>

5.2 不使用 th:fragment 来引用模块

<div id="copy-section">
&copy; 2018 Copyright by Lusifer.
</div>

我们可以用 CSS 的选择器写法来引入

<body>
...
<div th:include="footer :: #copy-section"></div>
</body>

5.3 th:include 和 th:replace 的区别

th:includeth:replace 都可以引入模块,两者的区别在于:

  • th:include:引入子模块的 children,依然保留父模块的 tag
  • th:replace:引入子模块的所有,不保留父模块的 tag

5.3.1 举个例子

定义待引入模块copy

<footer th:fragment="copy">
&copy; 2018 Copyright by Lusifer.
</footer>

分别用两种方式引入界面

<body>
...
<div th:include="footer :: copy"></div>

<div th:replace="footer :: copy"></div>
</body>

显示结果,th:include保留了div标签,而th:replace引入了整个copy模块去除了父标签

<body>
...

<div>
&copy; 2018 Copyright by Lusifer.
</div>

<footer>
&copy; 2018 Copyright by Lusifer.
</footer>

</body>

6 更多

更多详情,可以看官方手册,或者千峰博客
https://www.funtl.com/zh/spring-boot-thymeleaf/Thymeleaf-参考手册.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值