Spring Boot学习随笔- 第一个Thymeleaf应用(基础语法th:,request、session作用域取值)

学习视频:【编程不良人】2021年SpringBoot最新最全教程

第十五章、Thymeleaf

Thymeleaf是一种现代化的服务器端Java模板引擎,专门用于Web和独立环境。Thymeleaf在有网络和无网络的环境下皆可运行,即可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。它与Spring Boot集成良好,是Spring Boot官方支持的模板引擎之一。

  • 比较其他模板引擎

    目前主流模板引擎:Thymeleaf、FreeMarker、Groovy和Mustache

    整体来说:FreeMarker 在性能方面略有优势,但Thymeleaf在整体上胜出

注意:jsp可以直接在服务器访问,而Thymeleafa必须要经过控制器跳转访问

第一个Thymeleafaf网页

  1. 引入依赖

    xml 复制代码
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>**spring-boot-starter-thymeleaf**</artifactId>
    </dependency>
  2. 配置thymeleaf模板配置

    yaml 复制代码
    # THYMELEAF (ThymeleafAutoConfiguration)
    spring:
      thymeleaf:
        cache: false # 开启模板缓存(默认值: true ) 开发过程中改成false
        check-template: true # 检查模板是否存在,然后再呈现
        check-template-location: true # 检查模板位置是否正确(默认值 :true )
        servlet:
          content-type: text/html #Content-Type 的值(默认值: text/html )
        enabled: true # 开启 MVC Thymeleaf 视图解析(默认值: true )
        encoding: UTF-8 # 模板编码
        excluded-view-names:  # 要被排除在解析之外的视图名称列表,⽤逗号分隔
        mode: HTML5 # 要运⽤于模板之上的模板模式。另⻅ StandardTemplate-ModeHandlers( 默认值: HTML5)
        prefix: # 在构建 URL 时添加到视图名称前的前缀(默认值: classpath:/templates/ )
        suffix: # 在构建 URL 时添加到视图名称后的后缀(默认值: .html )
  3. 创建thymeleaf页面

  4. 开发Controller跳转thymeleaf

    java 复制代码
    @Controller
    @RequestMapping("hello")
    public class HelloController {
    		@RequestMapping("hello")
        public String hello() {
            System.out.println("hello thymeleaf ");
            return "index";
        }
    }

Thymeleaf语法使用

  1. html使用thymeleaf语法,必须引入命名空间

    html 复制代码
    <html lang="en" xmlns:th="http://www.thymeleaf.org">

    **th 可以用于html标签的任意属性,非常方便,它允许在HTML、XML、JavaScript、CSS甚至纯文本中处理模板。th命名空间允许我们在HTML标签的任何属性中使用Thymeleaf表达式,这样我们可以将模型数据动态地绑定到HTML标签的属性中。**

  2. 基本数据传递,**th:text**属性取值

    java 复制代码
    @RequestMapping("demo")
    public String demo(HttpServletRequest request, Model model) {
        System.out.println("hello thymeleaf ");
        request.setAttribute("name", "小陈");
        model.addAttribute("age", 22);
        return "demo";
    }
    html 复制代码
    <!doctype html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试thymeleaf语法</title>
    </head>
    <body>
        <h1>thymeleaf基本语法</h1>
    		thymeleaf取值的方式和jstl差不多,不过必须要在html标签里使用,通过${},括号
    里面填入作用域存的属性名
        <h4>获取request作用域的基本数据 <span **th:text="${name}"**></span></h4>
        <h4>获取request作用域的基本数据 <span **th:text="${age}"**></span></h4>
    </body>
    </html>
    • th:utext 属性

      **th:utext**会将文本内容作为原始HTML代码进行处理,不会进行HTML转义。这意味着如果后端传递的文本内容包含HTML标签,这些标签会被直接渲染为HTML元素,而不是作为纯文本显示。

    • 直接在标签的value前面加上th前缀,也可以取值,例如:

      html 复制代码
      <input type="text" name="name" **th:value="${name}"**>
  3. 获取对象类型

    html 复制代码
    <h2>获取对象类型:</h2>
    <table border="1" width="500">
        <tr>
            <th>id</th>
            <th>name</th>
            <th>salary</th>
            <th>birthday</th>
        </tr>
        <tr>
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${user.salary}"></td>
            <!--格式化日期-->
            <td th:text="${#dates.format(user.birthday,'yyyy-MM-dd HH:mm:ss')}"></td>
        </tr>
    </table>
  4. 获取集合类型

    通过th:each属性进行遍历,例如**th:each="user:${users}"**

    html 复制代码
    <h2>获取集合类型:</h2>
    <!--遍历集合:th:each-->
    <table border="1" width="500">
        <tr>
            <th>id</th>
            <th>name</th>
            <th>salary</th>
            <th>birthday</th>
        </tr>
        <tr **th:each="user:${users}"**>
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${user.salary}"></td>
            <!--格式化日期-->
            <td th:text="${#dates.format(user.birthday,'yyyy-MM-dd HH:mm:ss')}"></td>
        </tr>
    </table>

    执行效果:成功获取

    • 通过遍历状态获取信息

      html 复制代码
      <tr th:each="user,state:${users}">
          <td th:text="计数+${state.count}"></td>
          <td th:text="'判断偶数行:'+${state.odd}"></td>
          <td th:text="'判断奇数行:'+${state.even}"></td>
          <td th:text="'集合长度=:'+${state.size}"></td>
          <td th:text="${user.id}"></td>
          <td th:text="${user.name}"></td>
          <td th:text="${user.salary}"></td>
          <!--格式化日期-->
          <td th:text="${#dates.format(user.birthday,'yyyy-MM-dd HH:mm:ss')}"></td>
      </tr>

      执行效果:

  5. 通过th:if有条件展示数据

    html 复制代码
    <div th:if="${user.role == 'admin'}">
        <p>您是管理员,拥有特殊权限。</p>
    </div>
    <div th:if="${user.role == 'manager'}">
        <p>您是经理,可以管理团队。</p>
    </div>
    <div th:if="${user.role == 'employee'}">
        <p>您是普通员工,完成日常工作。</p>
    </div>
  6. 获取session作用域数据,加上session前缀即可

    html 复制代码
    <h2>获取session作用域中数据:<span th:text="${session.name}"></span></h2>
  7. 获取项目名地址

    通过**th:href="@{/demo.css}"**的方式获取,常用于重定向跳转的时候访问不到css文件的时候,使用根目录路径

    html 复制代码
    <link rel="stylesheet" th:href="@{/demo.css}">
相关推荐
非优秀程序员20 分钟前
第07章 孙德良的阳谋|《互联网产品恩仇录》
javascript·后端
非优秀程序员20 分钟前
第06章 浙江帮的内战|《互联网产品恩仇录》
后端
非优秀程序员20 分钟前
第08章 马云的反击|《互联网产品恩仇录》
后端
非优秀程序员28 分钟前
题记|《互联网产品恩仇录》
后端·程序员·创业
Godspeed Zhao36 分钟前
从零开始学AI25——无监督学习之层次聚类
学习·机器学习·聚类
Gopher_HBo4 小时前
Go CPU 剖析的"地基":信号、CAS、写屏障、无锁环形缓冲
后端
panbook4 小时前
从0到1实现一个分布式时序数据库(二):写入成功之后,如何用 WAL 找回数据
后端
Swot5 小时前
上传一张 4MB 图片,我先后撞上了三层请求体限制
后端
IT_陈寒5 小时前
Vite的HMR把我整不会了:一个生产环境的热更新坑
前端·人工智能·后端
OLRainM5 小时前
实习复盘:大模型网关渠道质量评分实战(二)—— 报错了到底算谁的锅?流式归因与 Token 补账踩过的 8 个真坑
后端