Springboot整合Thymeleaf 模板引擎(案例)- 语法详解

Thymeleaf 模板引擎详解 + 整合Springboot开发案


1、什么是Thyeleaf 模板引擎?

1.1 Thymeleaf 简介

简单说,Thymeleaf是一个流行的模板引擎,是基于HTML的,语法应用在HTML标签中。该模板引擎采用java语言开发。
从代码层次上讲:Thymeleaf是一个java类库,他是一个xml/xhtml/html5的模板引擎,可以作为mvc的web应用的view层。
thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。

Thymeleaf 是新一代 Java 模板引擎,与 Velocity、FreeMarker 等传统 Java 模板引擎不同,Thymeleaf 支持 HTML 原型,其文件后缀为“.html”,因此它可以直接被浏览器打开,此时浏览器会忽略未定义的 Thymeleaf 标签属性,展示 thymeleaf 模板的静态页面效果;当通过 Web 应用程序访问时,Thymeleaf 会动态地替换掉静态内容,使页面动态显示。

模板引擎的作用:

​ 模板引擎是做视图层工作的,在服务器端将Controller传过来的数据替换掉模板上的静态数据。(模板+数据=展示页面) Java生态下的模板引擎有:Thymeleaf、Freemaker、Velocity、Beetl等。

Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。

这里为大家学习提供两个链接:

Thymeleaf 的官方网站:http://www.thymeleaf.org

Thymeleaf 官方手册:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

官方手册是纯英文,不适合学习,这里给大家一个中文的学习文档,非常好用:

Thymeleaf教程(10分钟入门)网站:http://c.biancheng.net/spring_boot/thymeleaf.html

2、入门案例

2.1 创建Springboot项目

在这里插入图片描述

选择需要的依赖 和 稳定的Springboot版本,重点添加:web和Thyeleaf 模板引擎依赖

在这里插入图片描述

可以看到,再pom.xml配置文件中,已经引入了thymeleaf 模板引擎的依赖了!

<!--thymeleaf起步依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>	

2.2 在resources/templates目录下创建index.html

  1. 在html根元素添加命名空间声明:xmlns:th="http://www.thymeleaf.org"
    在这里插入图片描述

  2. 在html标签内引用thymeleaf的语法:th:text="${data}",接收key为data的数据,替换所修饰标签内的文本内容。

2.3 创建Controller

​ 在java代码中,也就是Springboot中!进行 Controller代码的编写:

@Controller
public class ThymeleafController {
    @GetMapping("/find")
    public String find(Model model) {
        //向请求作用域中写入数据
        model.addAttribute("data","Hello Thymeleaf");
        //返回视图
        return "index";
    }
}

2.4 编写 thyeleaf模板代码

​ 在 index.html页面,编写 thyeleaf模板代码,也就是html标签中:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><!--1.添加命名空间声明-->
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--2.引用thymeleaf语法-->
    <h2 th:text="${data}">测试数据</h2>
</body>
</html>

2.5 启动应用,在浏览器中发送请求: http://localhost:8080/find

在这里插入图片描述

3、 模板引擎的常用设置

Controller方法返回的是逻辑视图名称,但我们并没有设置视图解析器,也能访问到页面。这是因为Thymeleaf在核心配置文件中有一些默认的设置,如下

##Thymeleaf默认设置
#缓存 默认为true,但在开发阶段为了修改立即生效,需设置为false
spring.thymeleaf.cache=false
#模板使用的字符编码格式
spring.thymeleaf.encoding=UTF-8
#模板类型  默认为HTML,模板是html文件
spring.thymeleaf.mode=HTML
#模板视图前缀 默认设置为 classpath:/templates/
spring.thymeleaf.prefix=classpath:/templates/
#模板视图后缀 默认为 .html
spring.thymeleaf.suffix=.html

4、 Thymeleaf 语法规则

在使用 Thymeleaf 之前,首先要在页面的 html 标签中声明名称空间,示例代码如下。

xmlns:th="http://www.thymeleaf.org"

在 html 标签中声明此名称空间,可避免编辑器出现 html 验证错误,但这一步并非必须进行的,即使我们不声明该命名空间,也不影响 Thymeleaf 的使用。

Thymeleaf 作为一种模板引擎,它拥有自己的语法规则。Thymeleaf 语法分为以下 2 类:

  • 标准表达式语法
  • th 属性

4.1 标准表达式语法

Thymeleaf 模板引擎支持多种表达式:

  • 变量表达式:${…}
  • 选择变量表达式:*{…}
  • 链接表达式:@{…}
  • 国际化表达式:#{…}
  • 片段引用表达式:~{…}
4.1.1 变量表达式

使用 ${} 包裹的表达式被称为变量表达式,该表达式具有以下功能:

  • 获取对象的属性和方法
  • 使用内置的基本对象
  • 使用内置的工具对象
① 获取对象的属性和方法

使用变量表达式可以获取对象的属性和方法,例如,获取 person 对象的 lastName 属性,表达式形式如下:

${person.lastName}
② 使用内置的基本对象

使用变量表达式还可以使用内置基本对象,获取内置对象的属性,调用内置对象的方法。 Thymeleaf 中常用的内置基本对象如下:

  • #ctx :上下文对象;
  • #vars :上下文变量;
  • ……

例如,我们通过以下 2 种形式,都可以获取到 session 对象中的 map 属性:

纯文本复制
${#session.getAttribute('map')}${session.map}

③ 使用内置的工具对象

除了能使用内置的基本对象外,变量表达式还可以使用一些内置的工具对象。

  • strings:字符串工具对象,常用方法有:equals、equalsIgnoreCase、length、startsWith,contains 和 containsIgnoreCase 等;
  • bools:布尔工具对象,常用的方法有:isTrue 和 isFalse 等;
  • arrays:数组工具对象,常用的方法有:toArray、length、isEmpty、contains 和 containsAll 等;
  • lists/sets:List/Set 集合工具对象,常用的方法有:toList、size、isEmpty、contains、containsAll 和 sort 等;
  • dates:日期工具对象,常用的方法有:format、year、month、hour 和 createNow 等。
  • ………

例如,我们可以使用内置工具对象 strings 的 equals 方法,来判断字符串与对象的某个属性是否相等,代码如下。

${#strings.equals('编程帮',name)}
2、4.1.2 选择变量表达式

选择变量表达式与变量表达式功能基本一致,只是在变量表达式的基础上增加了与 th:object 的配合使用。当使用 th:object 存储一个对象后,我们可以在其后代中使用选择变量表达式({…})获取该对象中的属性,其中,“”即代表该对象。

<div th:object="${session.user}" >    <p th:text="*{fisrtName}">firstname</p></div>

th:object 用于存储一个临时变量,该变量只在该标签及其后代中有效,在后面的内容“th 属性”中我详细介绍。

在此还有: 链接表达式、 国际化表达式、片段引用表达式,在此不过多的介绍,按自己的开发需求,在我发的中文文档链接中可以学习,并使用!!!

5、 常用基本属性

Thymeleaf的大部分属性和html元素的属性一样。

在html元素属性前加上th:前缀之后,属性的作用不变,属性的值由模板引擎处理。

注意:在Thymeleaf属性中可以使用变量表达式。

1、th:action

作用同form表单标签的action属性,主要结合链接表达式,获取动态变量。

<form th:action="@{/tmp/doSome(id=${id})}" th:method="post" >...</form>

2、th:method

同form表单的method属性。

<form th:action="@{/tmp/doSome(id=${id})}" th:method="post" >...</form>

3、th:href

定义超链接,主要结合链接表达式,获取动态变量。

<a th:href="@{/getStudent(id=${id},name=${name})}">传参数方式 2</a>

4、th:src

同html的src属性,用于引入外部资源,常与链接表达式结合使用。

在Spring Boot项目中,所有静态资源都放到resources的static目录下,引如此目录下的资源时,路径上不需要写上static。

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

5、th:text

用于文本的显示,该属性显示的文本在标签体中,如果是文本框,数据会在文本框外显示,要想显示在文本框内显示,需要使用 th:value。

<h3 th:text="${title}"></h3>
<input type="text" th:text="${preText}" name="username" th:value="${username}"  >

6、 th:style

设置样式

<div th:style="'color: red'"></div>

5.2 th:each 遍历集合

th:each用于遍历后台传过来的集合。

用法:

①创建Controller方法

向请求作用域中存入一个List集合,集合中的元素是Student对象。

@RequestMapping("/each")
public String each(Model model) {
    List<Student> studentList = new ArrayList<>();
    studentList.add(new Student("张三",19,"zhangsan@qq.com"));
    studentList.add(new Student("李四",20,"lisi@qq.com"));
    studentList.add(new Student("王五",21,"wangwu@qq.com"));
    studentList.add(new Student("赵六",22,"zhaoliu@qq.com"));
    model.addAttribute("studentList",studentList);
    return "each_test";
}
②创建each_test.html页面

在templates目录下创建 each_test.html,使用Thymeleaf的th:each属性将集合中的数据遍历展示在表格中。

<center>
    <table cellpadding="0" cellspacing="0" border="1" width="300px">
        <thead>
            <tr>
                <th>序号</th>
                <th>下标</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>邮箱地址</th>
                <th>是否为第一行</th>
                <th>姓名2</th>
            </tr>
        </thead>
        <tbody th:each="student,itemStat:${studentList}">
            <tr>
                <td th:text="${itemStat.count + '/' + itemStat.size}"></td>
                <td th:text="${itemStat.index}"></td>
                <td th:text="${student.name}"></td>
                <td th:text="${student.age}"></td>
                <td th:text="${student.email}"></td>
                <td th:text="${itemStat.first}"></td>
                <td th:text="${itemStat.current.name}"></td>
            </tr>
        </tbody>
    </table>
</center>

语法说明:th:each="student,itemStat:${studentList}"

  • ${studentList}:后台传过来的待遍历集合。
  • student:自定义变量,代表当前迭代元素。
  • itemStat;自定义变量,代表当前循环体的信息,该变量可以获取如下信息(改名字可自定义)
    • index:当前迭代元素的下标(从0开始算)
    • count:当前迭代元素的个数(从1开始算)
    • size:集合中元素的数量
    • even/odd:布尔值,当前循环是否是偶数/奇数(从0开始算)
    • first:布尔值,当前迭代元素是否是集合中第一个元素
    • last:布尔值,当前迭代元素是否是集合中最后一个元素
    • current:获取当前迭代元素,即student
③开启应用,在浏览器访问 http://localhost:8080/each

在这里插入图片描述

5.3 if 条件判断

语法:

  • th:if="boolean条件" ,条件为true时显示所修饰标签里的内容
  • th:unless="boolean条件",条件为false时显示所修饰标签里的内容

6、Springboot整合Thyeleaf

6.1 创建Springboot项目,添加Thyeleaf模板引擎+web开发

在上面的教程中,已经做了创建项目的样式!可在前面的文档中查看,并创建项目!

6.2 对application.yml 进行编写规范和需求

这里是我自己的,按照这个模板改为自己的即可!!

server:
  port: 8081
# thyeleaf 
spring:
  thymeleaf:
    cache: false
    mode: HTML
    encoding: UTF-8
    prefix: classpath:/templates/
    suffix: .html
    servlet:
      content-type: text/html
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/t149?characterEncoding=utf-8&serverTimezone=GMT%2B8
    username: root
    password: root
# mybatis
mybatis:
  mapper-locations: classpath:/com/ithjc/mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  type-aliases-package: com.ithjc.pojo

6.3 创建数据库 和 苹果表

数据库命名:fruits

苹果表命名:apple

-- 创建数据库
create database fruits;
-- 创建表
CREATE TABLE `apple`  (
  `aid` int NOT NULL,
  `aname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `acolor` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`aid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- 添加数据
INSERT INTO `apple` VALUES (1, '苹果', '黄色');
INSERT INTO `apple` VALUES (2, '苹果', '蓝色');
INSERT INTO `apple` VALUES (3, '苹果', '蓝色');
INSERT INTO `apple` VALUES (4, '苹果', '蓝色');

6.4 编写实体类

注解 @Data是lombok依赖!

@Data
public class Apple {
    private Integer aid;
    private String aneme;
    private String acolor;
}

Lombok依赖:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

6.5 编写mapper接口 ,数据访问层

注解@Mapper 是mybatis依赖!

AppleMapper 接口

@Mapper
public interface AppleMapper {
	//查询所有苹果信息
    List<Apple> findAll();
}

mybatis依赖导入:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

6.6 编写 service接口 和 Impl实现类,业务逻辑层

AppleService 接口

public interface AppleService {
    List<Apple> findAll();
}

AppleServiceImpl 类

@Service
public class AppleServiceImpl implements AppleService {
    @Autowired
    private AppleMapper appleMapper;
    
    @Override
    public List<Apple> getAll() {
        return appleMapper.findAll();
    }
}

6.7 resources 下编写mapper.xml文件

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ithjc.mapper.AppleMapper">
    <select id="findAll" resultType="com.ithjc.pojo.Apple">
    select * from apple;
    </select>
</mapper>

6.8 编写Controller

@Controller
public class AppleController {

    @Autowired
    private AppleService appleService;

    @RequestMapping("/getAll")
    public String getAll(Model model){
        List<Apple> all = appleService.getAll();
        model.addAttribute("apples",all);
        return "apple";
    }
}

6.9 编写apple.html 页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>苹果列表</title>
    </head>
    <body>
        <table border="1">
            <tr>
                <th>苹果编号</th>
                <th>苹果名称</th>
                <th>苹果颜色</th>
            </tr>
            <tr th:each="apple : ${apples}">
                <td th:text="${apple.aid}"></td>
                <td th:text="${apple.aname}"></td>
                <td th:text="${apple.acolor}"></td>
            </tr>
        </table>
    </body>
</html>

实现页面跳转

编写http请求:localhost:8080/getAll
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值