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

发布时间 2023-12-24 22:34:34作者: 扬眉剑出鞘

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

第十五章、Thymeleaf

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

  • 比较其他模板引擎

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

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

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

第一个Thymeleafaf网页

  1. 引入依赖

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

    # 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

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

Thymeleaf语法使用

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

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

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

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

    @RequestMapping("demo")
    public String demo(HttpServletRequest request, Model model) {
        System.out.println("hello thymeleaf ");
        request.setAttribute("name", "小陈");
        model.addAttribute("age", 22);
        return "demo";
    }
    
    <!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前缀,也可以取值,例如:

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

    <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}"**

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

    执行效果:成功获取

    • 通过遍历状态获取信息

      <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有条件展示数据

    <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前缀即可

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

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

    <link rel="stylesheet" th:href="@{/demo.css}">