2023-12-21 11:16

SpringBoot自带模板引擎Thymeleaf使用详解

少尉

JavaEE

(274)

(0)

收藏

前言

        Thymeleaf是一款用于渲染XML/HTML5内容的模板引擎,类似JSP。它可以轻易的与SpringMVC等Web框架进行集成作为Web应用的模板引擎。在SpringBoot中推荐使用Thymeleaf编写动态页面。

        Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。Thymeleaf在有网络和无网络的环境下皆可运行,它即可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。没有数据时,Thymeleaf的模板可以静态地运行;当有数据返回到页面时,Thymeleaf标签会动态地替换掉静态内容,使页面动态显示。

引入Thymeleaf起步依赖需要再pom.xml添加以下代码

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

一、SpringBoot静态资源相关目录

SpringBoot项目中没有WebApp目录,只有src目录。在src/main/resources 下面有 static 和 templates 两个文件夹。SpringBoot默认在static 目录中存放静态资源,而 templates 中放动态页面。

static目录

SpringBoot通过 /resources/static 目录访问静态资源

除了 /resources/static 目录,SpringBoot还会扫描以下位置的静态资源:

/resources/META‐INF/resources/

/resources/resources/

/resources/public/

templates目录

在SpringBoot中不推荐使用JSP作为动态页面,而是默认使用Thymeleaf编写动态页面。templates目录是存放Thymeleaf页面的目录。

二、变量输出

2.1 在templates目录下创建视图index.html

要想使用thymeleaf则必须引入他的命名空间http://www.thymeleaf.org

<!DOCTYPE html>
<!-- 引入thymeleaf命名空间,方便使用thymeleaf属性 -->
<html
    xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf入门</title>
</head>
<body>
    <!-- 静态页面显示程序员,动态页面使用后端传来的msg数据代替 -->
    <h1 th:text="${msg}">程序员</h1>
</body>

2.2 创建对应的Controller

因为template中的html文件不能直接访问,需要编写Controller跳转到页面中。代码如下:

@Controller
public class PageController {
  // 页面跳转
  @GetMapping("/show")
  public String showPage(Model model){
    model.addAttribute("msg","Hello
Thymeleaf");
    return "index";
 }
}

2.3 在视图展示model中的值

<span th:text="${msg}"></span>
<hr/>
<input th:value="${msg}">

三、操作字符串和时间

3.1 操作字符串

Thymeleaf提供了一些内置对象可以操作数据,内置对象可直接在模板中使用,这些对象是以#引用的,操作字符串的内置对象为strings。

strings常用方法

${#strings.isEmpty(key)} 判断字符串是否为空,如果为空返回true,否则返回false
${#strings.contains(msg,'T')} 判断字符串是否包含指定的子串,如果包含返回true,否则返回false
${#strings.startsWith(msg,'a')} 判断当前字符串是否以子串开头,如果是返回true,否则返回false
${#strings.endsWith(msg,'a')} 判断当前字符串是否以子串结尾,如果是返回true,否则返回false
${#strings.length(msg)} 返回字符串的长度
${#strings.indexOf(msg,'h')} 查找子串的位置,并返回该子串的下标,如果没找到则返回-1
${#strings.substring(msg,2,5)} 截取子串,用法与JDK的 subString 方法相同
${#strings.toUpperCase(msg)} 字符串转大写
${#strings.toLowerCase(msg)} 字符串转小写

使用方法

<span th:text="${#strings.isEmpty(msg)}"></span><hr>
<span th:text="${#strings.contains(msg,'s')}"></span><hr>
<span th:text="${#strings.length(msg)}"></span><hr>

3.2 操作时间

操作时间的内置对象为dates

内置对象dates常用方法

${#dates.format(key)} 格式化日期,默认的以浏览器默认语言为格式化标准
${#dates.format(key,'yyyy/MM/dd')} 按照自定义的格式做日期转换
${#dates.year(key)} 取年
${#dates.month(key)} 取月
${#dates.day(key)} 取日

准备数据

model.addAttribute("date",new Date());

使用示例

<span th:text="${#dates.format(date,'YYYY-MM-dd')}"></span><hr>
<span th:text="${#dates.year(date)}"></span><hr>
<span th:text="${#dates.month(date)}"></span><hr>
<span th:text="${#dates.day(date)}"></span><hr>

0条评论

点击登录参与评论