Thymeleaf(看这一篇就够了)

在这里插入图片描述

Thymeleaf

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

Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。

Thymeleaf在有服务和无服务的环境下皆可运行,它即可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果

没有服务时,Thymeleaf的模板可以展示静态数据;当有数据返回到页面时,Thymeleaf会动态地替换掉静态内容,使页面动态显示。

  1. 创建SpringBoot项目

  2. 引入SpringMVC和Thymeleaf起步依赖

<!--添加Thymeleaf起步依赖-->
<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>
  1. 创建视图index.html
<!DOCTYPE html>
<!-- 引入thymeleaf命名空间,方便使用thymeleaf属性 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>thymeleaf入门</title>
</head>
<body>
<!-- 静态页面显示中北小萌新,动态页面使用后端传来的msg数据代替 -->
<!-- thymeleaf支持el表达式 -->
<h2 th:text="${msg}">中北小萌新</h2>
</body>
</html>
  1. template中的html文件不能直接访问,需要编写Controller跳转到页面中
@Controller
public class PageController {
  // 页面跳转
  @GetMapping("/show")
  public String showPage(Model model){
    model.addAttribute("msg","Hello Thymeleaf");
    return "index";
   }
}
  1. 进行springboot配置
#日志格式
logging.pattern.console=%d{HH:mm:ss.SSS} %clr(%-5level) ---  [%-15thread] %cyan(%-50logger{50}):%msg%n
  1. 启动项目,访问http://localhost:8080/show及静态页面

变量输出

语法作用
th:text将model中的值作为内容放入标签中
th:value将model中的值放入input标签的value属性中

准备模型数据

@GetMapping("/show")
public String showPage(Model model){
  model.addAttribute("msg","Hello Thymeleaf");
  return "index";
}

在视图展示model中的值

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

操作字符串&时间

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

操作字符串
操作字符串的内置对象为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>

操作时间
操作时间的内置对象为dates

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

准备数据

model.addAttribute("date",new Date(130,0,1));

使用内置对象操作时间

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

条件判断

语法作用
th:if条件判断

准备数据

model.addAttribute("sex","女");

进行条件判断

<div>
  <span th:if="${sex} == '男'">
     性别:男
  </span>
  <span th:if="${sex} == '女'">
     性别:女
  </span>
</div>
语法作用
th:switch/th:caseth:switch/th:case与Java中的switch语句等效。th:case="“表示Java中switch的default,即没有case的值为true时显示th:case=”"的内容。

准备数据

model.addAttribute("id","12");

进行条件判断

<div th:switch="${id}">
  <span th:case="1">ID为1</span>
  <span th:case="2">ID为2</span>
  <span th:case="3">ID为3</span>
  <span th:case="*">ID为*</span>
</div>

迭代遍历

语法作用
th:each迭代器,用于循环迭代集合

遍历集合
编写实体类

public class User {
  private String id;
  private String name;
  private int age;
  // 省略getter/setter/构造方法
}

准备数据

List<User> users = new ArrayList();
users.add(new User("1","sxt",23));
users.add(new User("2","baizhan",22));
users.add(new User("3","admin",25));
model.addAttribute("users",users);

在页面中展示数据

<table border="1" width="50%">
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <!-- 遍历集合的每一项起名为user -->
  <tr th:each="user : ${users}">
    <td th:text="${user.id}"></td>
    <td th:text="${user.name}"></td>
    <td th:text="${user.age}"></td>
  </tr>
</table>

遍历Map
准备数据

Map<String,User> map = new HashMap();
map.put("user1",new User("1","sxt",23));
map.put("user2",new User("2","baizhan",22));
map.put("user3",new User("3","admin",25));
model.addAttribute("map",map);

遍历map

<table border="1" width="50%">
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Age</th>
    <th>Key</th>
  </tr>
  <!-- 遍历出的是一个键值对对象,key获取键,value获取值 -->
  <tr th:each="m : ${map}">
    <td th:text="${m.value.id}"></td>
    <td th:text="${m.value.name}"></td>
    <td th:text="${m.value.age}"></td>
    <td th:text="${m.key}"></td>
  </tr>
</table>

使用状态变量

thymeleaf将遍历的状态变量封装到一个对象中,通过该对象的属性可以获取状态变量:

状态变量含义
index当前迭代器的索引,从0开始
count当前迭代对象的计数,从1开始
size被迭代对象的长度
odd/even布尔值,当前循环是否是偶数/奇数,从0开始
first布尔值,当前循环的是否是第一条,如果是返回true,否则返回false
last布尔值,当前循环的是否是最后一条,如果是则返回true,否则返回false

使用状态变量

<!--冒号前的第一个对象是遍历出的对象,第二个对象是封装状态变量的对象-->
<tr th:each="user,status : ${users}">
  <td th:text="${user.id}"></td>
  <td th:text="${user.name}"></td>
  <td th:text="${user.age}"></td>
  <td th:text="${status.index}"></td>
  <td th:text="${status.count}"></td>
  <td th:text="${status.size}"></td>
  <td th:text="${status.odd}"></td>
  <td th:text="${status.even}"></td>
  <td th:text="${status.first}"></td>
  <td th:text="${status.last}"></td>
</tr>

获取域中的数据

thymeleaf也可以获取request,session,application域中的数据,方法如下:

准备数据

request.setAttribute("req","HttpServletRequest");
session.setAttribute("ses","HttpSession");
session.getServletContext().setAttribute("app","application");

获取域数据

request:<span th:text="${req}"></span><hr/>
session: <span th:text="${session.ses}"/><hr/>
application: <span th:text="${application.app}"/>

URL写法

在Thymeleaf中路径的写法为@{路径}

<a th:href="@{http://www.baidu.com}">百度</a>
<a th:href="@{http://www.baidu.com?id=1&name=sxt}">静态参数一</a>
<a th:href="@{http://www.baidu.com(id=2,name=bz)}">静态参数二</a>

添加动态参数
准备数据

model.addAttribute("id","100");
model.addAttribute("name","bzcxy");

在URL中添加参数

<a th:href="@{'http://www.baidu.com?id='+${id}+'&name='+${name}}">动态参数一</a>
<a th:href="@{http://www.baidu.com(id=${id},name=${name})}">动态参数二</a>

添加RESTful风格的参数

<a th:href="@{http://www.baidu.com/{id}/{name}(id=${id},name=${name})}">restful格式传递参数方式</a>

相关配置

在SpringBoot配置文件中可以进行Thymeleaf相关配置

配置项含义
spring.thymeleaf.prefix视图前缀
spring.thymeleaf.suffix视图后缀
spring.thymeleaf.encoding编码格式
spring.thymeleaf.servlet.content-type响应类型
spring.thymeleaf.cache=false页面缓存,配置为false则不启用页面缓存,方便测试
spring:
  thymeleaf:
   prefix: classpath:/templates/
   suffix: .html
   encoding: UTF-8
   cache: false
   servlet:
    content-type: text/html

如果我的内容对你有帮助,请点赞,评论,收藏。创作不易,大家的支持就是我坚持下去的动力
在这里插入图片描述

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Thymeleaf是一个流行的Java服务器端模板引擎,用于在Web开发中动态生成HTML页面。它允许开发人员将业务逻辑和页面模板结合,使得前后端开发更加灵活和高效。 首先,Thymeleaf与传统的JSP相比,具有更加简洁的语法和更好的可读性。Thymeleaf使用自然的HTML语法,并采用属性型的编程方式,从而使得模板文件更易于理解和维护。它还提供了丰富的标签库和表达式语言,可以方便地进行逻辑判断、循环遍历和数据绑定等操作。 其次,Thymeleaf具有强大的扩展性和可定制性。它支持自定义标签和表达式,可以根据项目的需求进行二次开发。开发者可以自定义标签库,将通用的HTML组件封装成标签,提高代码的复用性。此外,Thymeleaf还支持国际化和主题切换等功能,可以方便地实现多语言和多样式的页面。 另外,Thymeleaf还具有良好的与Spring框架的集成能力。它可以与Spring MVC无缝集成,利用Spring的依赖注入和AOP等特性,更好地处理请求和响应。在Spring Boot项目中使用Thymeleaf,只需添加相应的依赖和配置,即可快速搭建起一个完整的Web应用。 总结来说,Thymeleaf是一个功能强大且易于使用的模板引擎,可以大大简化Web开发的工作量。它具有简洁的语法、强大的扩展性和与Spring框架的良好集成能力,使得开发人员可以更加方便地实现动态页面的生成和展示。无论是小型项目还是大型企业级应用,Thymeleaf都是一个值得推荐的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

中北萌新程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值