从01开始 从01开始
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)

peterjxl

人生如逆旅,我亦是行人
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)
  • JavaSE

  • JavaSenior

  • JavaEE

  • JavaWeb

  • Spring

  • 主流框架

  • SpringMVC

  • SpringBoot

    • SpringBoot教程-尚硅谷

      • SpringBoot课程介绍
      • Spring和SpringBoot
      • HelloWorld
      • 了解自动配置原理
      • 底层注解-@Configuration详解
      • 底层注解-@Import导入组件
      • 底层注解-@Conditional条件装配
      • 原生配置文件引入-@ImportResource
      • 底层注解-配置绑定@ConfigurationProperties
      • 自动配置原理
      • 自动配置流程
      • Lombok简化开发
      • DevTools
      • Spring-Initailizr
      • 配置文件-Yaml用法
      • Web开发简介
      • web开发-静态资源规则于定制化
      • 静态资源配置原理
      • Rest映射及源码解析
      • 请求映射原理
      • 常用参数注解使用
      • MatrixVariable:矩阵变量
      • 各种类型参数解析原理
      • Servlet-API参数解析原理
      • Model、Map参数解析原理
      • 自定义对象参数绑定原理
      • 自定义Converter原理
      • 数据响应原理
      • 内容协商原理
      • 基于请求参数的内容原理
      • 自定义MessageConverter原理
      • Thymeleaf初体验
        • 前言
        • Thymeleaf
        • 引入Thymeleaf
        • 新建Controller
        • 新建success.html
        • 测试
        • 源码
      • web实验-后台管理系统
      • web实验-抽取公共页面
      • web实验-遍历数据
      • 源码分析-视图解析器与视图
      • 拦截器-登录检查与静态资源放行
      • 拦截器的执行时机和原理
      • 单文件和多文件上传的使用
      • 文件上传原理
      • 错误处理机制
      • 错误处理-底层组件源码分析
      • 异常处理流程
      • 几种异常处理原理
      • Web原生对象注入
      • 嵌入式Servlet容器
      • 定制化原理
      • 数据库场景的自动配置分析和整合测试
      • 自定义方式整合Druid
      • 通过starter整合Druid
      • 整合Mybatis
      • 使用注解整合Mybatis
      • 整合MybatisPlus操作数据库
      • MybatisPlus-列表分页展示
      • 整合Redis
      • 单元测试-Junit5
      • 单元测试-断言机制
      • 单元测试-前置条件
      • 单元测试-嵌套测试
      • 单元测试-参数化测试
      • 指标监控-基本概念
      • 指标监控-配置EndPoint
      • 指标监控-可视化
      • 原理解析-Profile功能
      • 配置文件深入
      • 自定义Starter
      • SpringApplication初始化过程
      • SpringBoot完整启动过程
      • SpringBoot
  • Java并发

  • Java源码

  • JVM

  • 韩顺平

  • Java
  • Java
  • SpringBoot
  • SpringBoot教程-尚硅谷
2023-08-22
目录

Thymeleaf初体验

# 320.Thymeleaf初体验

接下来我们来到视图解析与模板引擎部分。   ‍

# 前言

所谓视图解析,就是SpringBoot处理完请求后,跳转要某个页面的过程。

在SpringMVC中,经常是用转发和重定向到一个JSP页面;

但SpringBoot默认打包方式是jar,这是一个压缩包,JSP不支持在压缩包内编译;因此SpringBoot是不支持JSP的,要实现页面跳转的功能,需要引入第三方模板引起技术实现页面渲染(其实JSP也是一种模板引擎)

SpringBoot支持freemarker,groovy-templates,thymeleaf等模板引擎(可以在官网文档的starter (opens new window)中看到),这里我们讲讲Thymeleaf

‍

# Thymeleaf

Thymeleaf是什么呢?根据官网 (opens new window)的描述

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

大意:Thymeleaf是一个现代化的,服务端的Java模板引擎

‍

优点:既然是面向后端,那么语法就挺简单的;

缺点:性能不是很高,如果是高并发,可以考虑前后端分离的方式来做

语法:使用的是自然语言的语法,和HTML很类似,例如:

<table>
  <thead>
    <tr>
      <th th:text="#{msgs.headers.name}">Name</th>
      <th th:text="#{msgs.headers.price}">Price</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="prod: ${allProducts}">
      <td th:text="${prod.name}">Oranges</td>
      <td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td>
    </tr>
  </tbody>
</table>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

官方文档地址:Documentation - Thymeleaf (opens new window)

‍

# 基本语法

‍

1、表达式(用来取值的)

表达式名字 语法 用途
变量取值 ${...} 获取请求域、session域、对象等值
选择变量 *{...} 获取上下文对象值(例如定义了一个Person对象)
消息 #{...} 获取国际化等值
链接 @{...} 生成链接(会自动加上项目的地址)
片段表达式 ~{...} 类似 jsp:include 的作用,引入公共页面片段

‍

2、字面量

  • 文本值: 'one text' , 'Another one!' ,…
  • 数字: 0 , 34 , 3.0 , 12.3 ,…
  • 布尔值: true , false
  • 空值: null
  • 变量: one,two,.... 变量不能有空格

‍

3、文本操作:字符串拼接: +, 变量替换: |The name is ${name}|

4、数学运算:运算符: + , - , * , / , %

5、布尔运算:运算符: and , or,一元运算: ! , not

6、比较运算:比较: > , < , >= , <= ( gt , lt , ge , le ) 等式: == , != ( eq , ne )

7、条件运算

  • If-then: (if) ? (then)
  • If-then-else: (if) ? (then) : (else),三元运算
  • Default: (value) ?: (defaultvalue)

‍

8、特殊操作:无操作: _

# 设置属性值-th:attr

设置单个标签的属性值:在标签里用th:attr​属性,例如第4行

<form action="subscribe.html" th:attr="action=@{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  </fieldset>
</form>
1
2
3
4
5
6

默认是第4行,会计算出value的属性值,然后替换掉属性 value 的值。原先value的值相当于是默认值。

‍

‍

设置多个值

<img src="../../images/gtvglogo.png"  th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
1

‍

‍

也可以用th:value​的写法替代上面的写法:

<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
<form action="subscribe.html" th:action="@{/subscribe}">
1
2

所有h5兼容的标签写法,参考Tutorial: Using Thymeleaf (opens new window)

‍

‍

# 迭代

<tr th:each="prod : ${prods}">
        <td th:text="${prod.name}">Onions</td>
        <td th:text="${prod.price}">2.41</td>
        <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
1
2
3
4
5

‍

<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
  <td th:text="${prod.name}">Onions</td>
  <td th:text="${prod.price}">2.41</td>
  <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
1
2
3
4
5

# 条件运算

<a href="comments.html"
th:href="@{/product/comments(prodId=${prod.id})}"
th:if="${not #lists.isEmpty(prod.comments)}">view</a>
1
2
3

‍

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>
1
2
3
4
5

‍

如果一个标签内写了多个属性,那么谁会生效呢?这就得提到属性的优先级了,参考文档10 Attribute Precedence (opens new window)

‍

# 引入Thymeleaf

在pom.xml中引入starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1
2
3
4

‍

引入之后,就会自动好了,通过自动配置类ThymeleafAutoConfiguration​;这个类会帮我们放几个组件(通过几个方法,上面加了@Bean注解):

  • ​SpringTemplateEngine​:模板引擎
  • ​ThymeleafViewResolver​:视图解析器

我们只需开发页面即可。

‍

我们在使用SpringMVC (opens new window)的时候,配置视图解析器 (opens new window)时要配置前缀和后缀等;Thymeleaf也要配置,不过已经有了默认配置,在ThymeleafProperties​类中;

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

    private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    //.....
1
2
3
4
5
6
7

也就是在resources/templates 文件夹下放HTML文件;

‍

# 新建Controller

新建一个Controller,用来跳转页面:

package com.peterjxl.boot.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ViewTestController {

    @GetMapping("/atguigu")
    public String atguigu(Model model){
        // model中的数据会被放在请求域中,相当于 request.setAttribute("msg", "hello, peterjxl!");
        model.addAttribute("msg", "hello, peterjxl!");
        model.addAttribute("link", "https://www.peterjxl.com");
        // 会被视图解析器处理,相当于 return thymeleaf/success.html;
        return "success";
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

‍

# 新建success.html

我们在resources/templates目录下,新建success.html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>

    </body>
</html>
1
2
3
4
5
6
7
8
9
10

‍

然后我们添加Thymeleaf的名称空间(这样写HTML时就有提示,建议加上):

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

‍

然后通过Thymeleaf的语法获取数据:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1 th:text="${msg}">哈哈</h1>
        <h2>
            <a href="www.baidu.com" th:href="${link}">去百度</a>
        </h2>
    </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13

‍

说明:

  • ​th:text​ 会替换掉标签里的文本数据,然后我们通过${}​的方式取出数据
  • ​th:href​ 会替换掉href属性的值(要替换掉哪个属性的值,只需加上 th:属性名​ 即可)

‍

# 测试

我们访问localhost:8888/atguigu (opens new window):

​​​​

‍

‍

# 源码

已将本文源码上传到Gitee (opens new window)或GitHub (opens new window) 的分支demo18,读者可以通过切换分支来查看本文的示例代码

在GitHub上编辑此页 (opens new window)
上次更新: 2023/8/23 10:10:57
自定义MessageConverter原理
web实验-后台管理系统

← 自定义MessageConverter原理 web实验-后台管理系统→

Theme by Vdoing | Copyright © 2022-2023 粤ICP备2022067627号-1 粤公网安备 44011302003646号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式