天天看点

JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

Spring Boot学习笔记

  • Spring Boot基础
    • Spring Boot简介
    • Spring Boot工程创建
      • 创建第一个SpringBoot工程 01-primary
      • 基于war的Spring Boot工程 01-primary-war
    • Spring Boot的主配置文件
      • properties文件
      • yml文件
    • Actuator监控器
      • 功能演示
      • 添加info信息
      • 开放其它监控终端
      • 单独关闭某些监控终端
      • 常用的监控终端
    • 自定义异常页面
      • 定义异常页面
      • 测试
    • 单元测试
      • 定义Service
      • 测试
  • 模板引擎Thymeleaf
    • Thymeleaf简介
    • Spring Boot集成Thymeleaf
    • Thymeleaf标准表达式
      • 变量表达式${...}
      • 选择表达式\*{...}
      • URL表达式@{...}
    • Thymeleaf常见属性
      • 官方在线文档
      • 逻辑运算相关属性
        • th:if
        • th:switch...th:case
        • th:each
          • 遍历List
          • 遍历状态对象
          • 遍历Map
      • html标签相关
        • th:text/th:utext
        • th:name...th:value
        • URL路径相关
      • css/js相关
        • th:id/th:name
        • th:style
        • th:onclick
      • 内联属性th:inline
        • 内联文本
        • 内联脚本
        • 内联CSS
      • 万能属性th:attr
        • 为无定义的属性赋予动态参数
        • 一次为多个属性赋予动态参数
    • Thymeleaf运算基础
      • Thymeleaf字面量
        • 文本字面量
        • 数字字面量
        • 布尔字面量
        • null字面量
      • Thymeleaf运算符
        • 字符串拼接运算符
        • 算术运算符
        • 关系运算符
        • 逻辑运算符
        • 条件运算符
    • Thymeleaf内置对象
      • Servlet API对象
      • 表达式实用对象
        • 工具对象简介
        • 应用举例

Spring Boot基础

Spring Boot简介

  • Spring Boot 是由 Pivotal[ˈpɪvətl]团队(一家做大数据的公司)提供的全新框架,其设计 目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配 置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot 致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
  • 简单来说,SpringBoot 可以简化 Spring 应用程序的开发,使我们不再需要 Spring 配置文 件及 web.xml 文件。
  • 2004 年 Spring 第一个版本诞生。
  • 2007 年成立 Spring Source 公司,框架更名为 Spring。
  • 2009 年 Spring Source 公司被 VMware 收购。
  • 2013 年由 VMware 公司及多家公司联合出资成立了 Pivotal 公司。
  • 2013 年 Pivotal 开始研发 Spring Boot,2014 年 Spring Boot 第一个版本诞生。

Spring Boot工程创建

  • 父工程 springboot-example-parent 依赖:
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.5.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
  <!-- spring-boot-starter-web -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <!-- spring-boot-starter-test -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
  <!-- commons-lang -->
  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
  </dependency>
  <!-- lombok依赖 -->
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
  </dependency>
</dependencies>
<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
  </plugins>
</build>
           

创建第一个SpringBoot工程 01-primary

  • 使用 IDEA 要创建一个 Spring Boot 的 Web 工程:新建 Spring Initializr,命名为 01-primary。
  • 启动类:
@SpringBootApplication
public class PrimaryApplication {
    public static void main(String[] args) {
        SpringApplication.run(PrimaryApplication.class, args);
    }
}
           
  • 在启动类所在的包下再创建一个子包,在其中编写 SpringMVC 的处理器类。注意要求:代码所在的包必须是启动类所在包的子孙包,不能是同级包。
@RestController
public class SomeController {
    @RequestMapping("/some")
    public String someHandle() {
        return "Hello Spring Boot World! ";
    }
}
           
  • 项目启动并测试接口:http://localhost:8080/some

基于war的Spring Boot工程 01-primary-war

  • 前面创建的 Spring Boot 工程最终被打为了 Jar 包,是以可执行文件的形式出现的,其使用了 Spring Boot 内嵌的 Tomcat 作为 Web 服务器来运行 web 应用的。
  • 但在实际生产环境下,对于访问量不大的应用,直接以 Jar 包的形式出现,使用起来是非常方便的,不用部署了。但对于访问量较大的 Web 工程,我们不能使用 Tomcat,而要使用更为高效的商业 web 容器,例如 JBOSS、WebLogic 等,此时我们需要的是 war 包而非 jar 包。
  • 复制 01-primary 工程,重命名为 01-primary-war,在此基础上修改,添加依赖:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-tomcat</artifactId>
  <scope>provided</scope>
</dependency>
           
  • 启动类:
@SpringBootApplication
public class PrimaryWarApplication {
    public static void main(String[] args) {
        SpringApplication.run(PrimaryWarApplication.class, args);
    }
}
public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(PrimaryWarApplication.class);
    }
}
           
  • 启动:在 idea下启动,访问方式与之前的也相同。但实际打包 mvn package,其会打为 war 包,内置的 tomcat 也不会被打包进去。
  • 部署:找到该 war 包,将其部署到 Tomcat 的 webapps 目录中,启动 Tomcat。

Spring Boot的主配置文件

properties文件

  • Spring Boot 的主配置文件是 src/main/resources 中默认创建的 spring.properties 文件。该文件打开后是没有自动提示功能的。此时可以打开 Project Structure 窗口,在 Modules 中选中没有自动提示的工程,点击+号,找到 Spring,将其添加可以。此时的配置文件就有了自动提示功能,包括 yml 文件也有了自动提示。
  • 例如,可以修改 Tomcat 端口号和应用上下文路径:
# 修改内置Tomcat端口号
server.port=8888
# 指定部署到内置Tomcat中应用的根路径
server.servlet.context-path=/xxx
           
  • 运行工程后,查看日志文件可以看到端口号与应用的根的确发生的变化,测试接口:http://localhost:8888/xxx/some。
  • 不过需要注意,这里指定的 Tomcat 的端口号及应用的根路径,仅仅是针对于内置 Tomcat 的,是测试时使用的。将工程打为 war 包后部署到真正的 Tomcat,这些配置是不起作用的,即 Tomcat 的端口号为真正 Tomcat 的端口号,而项目的根路径为 war 包名称。

yml文件

  • Spring Boot 的主配置文件也可使用 application.yml 文件。yml,也可写为 yaml。
  • 在开发之初 YAML 的本意是 Yet Another Markup Language(仍是一种标记语言)。后来为了强调这种语言是以数据为中心,而不是以标记为中心,所以将 YAML 解释为 Yaml Ain’t Markup Language(Yaml 不是一种标记语言)。它是一种直观的能够被电脑识别的数据序列化格式,是一个可读性高并且容易被人阅读,容易和脚本语言交互,用来表达多级资源序列的编程语言。
  • yml 与 properties 文件的主要区别是对于多级属性,即 key 的显示方式不同。yml 文件在输入时,只需按照点(.)的方式输出 key 即可,输入完毕后回车即出现了如下形式。该形式要求冒号后与值之间要有一个空格。不同级别的属性间要有两个空格的缩进。
  • 需要注意,很多脚本中的空格都是作为无效字符出现的,但 yml 脚本则是作为有效字符出现的,必须要保证空格的数量。
  • 在演示时需要注意:application.properties 与 application.yml 这两个文件只能有一个。要求文件名必须为 application。所以,此时可以将 application.properties 文件重命名为其它名字即可。

Actuator监控器

  • Actuator’æktʃʊˌeɪtə是 Spring Boot 提供的一个可插拔模块,用于对工程进行监控。其通过不同的监控终端实现不同的监控功能。其功能与 Dubbo 的监控中心类似,不同的是,Dubbo 的监控中心是需要专门部署的,而 Spring Boot 的 Actuator 是存在于每一个工程中的。

功能演示

  • 使用 01-primary 工程,添加依赖:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
           
  • 修改配置文件:
server.port=8888
server.servlet.context-path=/first

# actuator监控的端口号与上下文路径
management.server.port=9999
management.server.servlet.context-path=/xxx
# 指定监控终端的基本路径,默认为actuator
management.endpoints.web.base-path=/base
           
  • 启动该工程后在地址栏访问 http://localhost:9999/xxx/base/health,health 是一种监控终端,用于查看当前应用程序(微服务)的健康状况。

添加info信息

  • 修改配置文件:在配置文件中添加如下 Info 信息,则可以通过 info 监控终端查看到。
# 自定义info信息
info.company.name=abc
info.company.url=http://www.abc.com
info.company.addr=ShenZhen China

info.auth.name=yw
info.auth.dep=development

# 从 pom.xml 文件中读取相应的值
[email protected]@
[email protected]@
[email protected]@
[email protected]@
           
  • 访问测试:http://localhost:9999/xxx/base/info
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

开放其它监控终端

默认情况下,Actuator 仅开放了 health 与 info 两个监控终端,但其还有很多终端可用,不过,需要手工开放。

  • 修改配置文件:在配置文件中添加如下内容
# 开放所有监控终端,默认只开启了health和info监控终端
# 在yml中*号为关键字,需要将其使用双引号引起来"*"
management.endpoints.web.exposure.include=*
           
  • mappings终端:通过 mappings 终端,可以看到当前工程中所有的 URI 与处理器的映射关系,及详细的处理器方法及其映射规则。很实用。http://localhost:9999/xxx/base/mappings
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf
  • beans终端:可以查看到当前应用中所有的对象信息
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf
  • env终端:可以看到当前应用程序运行主机的所有软硬件环境信息
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

单独关闭某些监控终端

  • 在开放了所有监控终端的情况下,有些终端显示的信息并不想公开,此时可以单独关闭这些终端。
# 单独关闭env与beans监控终端
management.endpoints.web.exposure.exclude=env,beans
           
  • 访问测试:在关闭这些终端后,其它终端仍可继续使用
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

常用的监控终端

  • 在百度搜索“springboot actuator”即可找到如下表格:
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

自定义异常页面

  • 对于 404、405、500 等异常状态,服务器会给出默认的异常页面,而这些异常页面一般都是英文的,且非常不友好。我们可以通过简单的方式使用自定义异常页面,并将默认状态码页面进行替换。
  • 直接在前面的工程 01-primary 上修改即可,在 src/main/resources 目录下再定义新的目录 public/error,必须是这个目录名称。

定义异常页面

  • 在 error 目录中定义异常页面。这些异常页面的名称必须为相应的状态码,扩展名为 html。
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

测试

  • 修改处理器模拟 500 错误:
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf
  • 启动项目,并访问接口测试:http://localhost:8888/first/some

单元测试

  • 在工程 01-primary 上进行修改。

定义Service

  • 定义Service接口和两个实现类:实现类上要添加@Service 注解,以交给 Spring 容器来管理。
public interface SomeService {
    void doSome();
}
@Service
public class SomeServiceImpl implements SomeService {
    @Override
    public void doSome() {
        System.out.println("SomeServiceImpl的doSome()");
    }
}
@Service
public class OtherServiceImpl implements SomeService {
    @Override
    public void doSome() {
        System.out.println("OtherServiceImpl的doSome()");
    }
}
           

测试

  • 创建测试类:打开 src/test/java 中的测试类,在其中直接添加测试方法即可。
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    /**
     * 若接口只有一个实现类,则可以使用byType方式自动注入
     * 但现在有两个实现类,只能使用byName方式自动注入
     */
    @Autowired
    @Qualifier("someServiceImpl")
    private SomeService someService;

    @Autowired
    @Qualifier("otherServiceImpl")
    private SomeService otherService;

    @Test
    public void test01() {
        someService.doSome();
        otherService.doSome();
    }
}
           

模板引擎Thymeleaf

Thymeleaf简介

  • Thymeleaf[taɪm lif],百里香叶。Thymeleaf 是一个流行的模板引擎,该模板引擎采用 Java 语言开发。模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档。例如,用于网站的模板引擎就会生成一个标准的 HTML 文档。不同的语言体系中都有自己的模板引擎,例如,Java 中常见的模板引擎有 Velocity、Freemaker、Thymeleaf 等。不同的模板引擎都会具有自己的特定的标签体系,而 Thymeleaf 以 HTML 标签为载体,在 HTML 的标签下实现对数据的展示。
  • Thymeleaf 本身与 SpringBoot 是没有关系的,但 SpringBoot 官方推荐使用 Thymeleaf 作为前端页面的数据展示技术,SpringBoot 很好地集成了这种模板技术。
  • Thymeleaf 的官网为: http://www.thymeleaf.org。
  • 从官网可以看到,其目前提供两个版本:3.x 与 2.x。Spring Boot2.x 默认使用的是 Thymeleaf3.x 版本,而 Spring Boot1.x 则使用的是 Thymeleaf2.x 版本。

Spring Boot集成Thymeleaf

  • 直接在 01-primary 工程修改,添加依赖:
<!-- 模板引擎thymeleaf -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 热部署 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
  <scope>runtime</scope>
  <optional>true</optional>
</dependency>
           
  • 修改配置文件:
# 开发阶段,建议关闭thymeleaf缓存,否则可能会出现数据未更新情况。
spring.thymeleaf.cache=false
           
  • 定义处理器:
@Controller
public class ThymeleafController {
    @RequestMapping("/test/myindex")
    public String indexHandle(Model model) {
        model.addAttribute("welcome", "Hello Thymeleaf World");
        return "index";
    }
}
           
  • 定义 index.html 页面:在 src/main/resources/templates 目录下定义 index.html 页面。
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="${welcome}">这里将显示数据</p>
<div th:text="${welcome}">这里将显示数据</div>
<span th:text="${welcome}">这里将显示数据</span>
<hr>
<p th:if="${gender} == 'male'">男</p>
<p th:if="${gender} == 'female'">女</p>

</body>
</html>
           

Thymeleaf标准表达式

  • 常用的 Thymeleaf 标准表达式有三种。标准表达式都是用于获取代码中存放到 Model 中的属性值的,只不过获取方式不同而已。以下举例均在前面的 thymeleaf 工程基础上直接修改,无需再创建新的 Module。

变量表达式${…}

  • 使用${…}括起来的表达式,称为变量表达式。该表达式的内容会显示在 HTML 标签体文本处。
  • 该表达式一般都是通过 th:text 标签属性进行展示的。

选择表达式*{…}

  • 选择表达式,也称为星号表达式,其是使用*{…}括起来的表达式。一般用于展示对象的属性。该表达式的内容会显示在 HTML 标签体文本处。但其需要与 th:object 标签属性联用,先使用 th:object 标签选择了对象,再使用*{…}选择要展示的对象属性。该表达式可以有效降低页面中代码的冗余。
  • 不过,其也可以不与 th:object 标签联用,在*{…}中直接使用“对象.属性”方式,这种写法与变量表达式相同。
  • 该表达式一般都是通过 th:text 标签属性进行展示的。

URL表达式@{…}

  • 使用@{…}括起来,并且其中只能写一个绝对 URL 或相对 URL 地址的表达式,称为 URL 表达式。这个绝对/相对 URL 地址中一般是包含有动态参数的,需要结合变量表达式 ${…} 进行字符串拼接。
  • @{…} 中的 URL 地址具有三种写法。为了演示这三种写法的区别,先为当前工程添加一个上下文路径,然后直接在 index.html 文件中修改。

Thymeleaf常见属性

官方在线文档

  • Thymeleaf 的属性很多,从官网的 Docs 模块的在线文档中可以看到。https://www.thymeleaf.org/documentation.html。
    JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

逻辑运算相关属性

th:if

该属性用于逻辑判断,类似于 JSTL 中的<c:if/>。

th:switch…th:case

该属性用于多分支判断,类似于 Java 中的 Swith-Case 语句。

<div th:switch="${age/10}">
	<p th:case="0">儿童</p>
	<p th:case="1">青少年</p>
	<p th:case="2">青年</p>
	<p th:case="3">中青年</p>
	<p th:case="4">中年</p>
	<p th:case="5">中老年</p>
	<p th:case="*">老年</p>
</div>
           

th:each

该属性用于遍历数组、List、Set、Map,类似于 JSTL 中的<c:forEach/>。

遍历List
Student student1 = new Student("张三", 23);
Student student2 = new Student("李四", 24);

List<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);

model.addAttribute("students", students);
           
<p th:each="stu : ${students}">
	<span th:text="${stu.name}"><span>
	<span th:text="${stu.age}"><span>
</p>
           
遍历状态对象
  • 如何获取到当前遍历的状态信息呢?例如,当前遍历的是第几个,当前遍历的是集合中索引号为多少的元素,这个索引号是奇数还是偶数等。这些状态信息被定义在一个状态对象中,而这个状态对象有两种获取方式,一种是在 th:each 中指定,一种是在当前遍历变量名后添加 Stat 后辍。
  • 常见的状态对象属性:
* index: 当前遍历对象的索引号(从 0 开始计算)
* count: 当前遍历对象是第几个(从 1 开始计算)
* even/odd: 布尔值,当前遍历对象的索引号是否是偶数/奇数(从 0 开始计算)
* first/last: 布尔值,当前遍历对象是否是第一个/最后一个
           
<p th:each="stu, xxx : ${students}">
	<!-- 声明状态对象为xxx -->
	<span th:text="${xxx.count}"><span>
	<span th:text="${stu.name}"><span>
	<span th:text="${stu.age}"><span>
</p>
<hr/>
<p th:each="stu, xxx : ${students}">
	<!-- 状态对象为当前遍历对象加Stat后缀 -->
	<span th:text="${stuStat.index}"><span>
	<span th:text="${stu.name}"><span>
	<span th:text="${stu.age}"><span>
</p>
           
遍历Map
  • 需要清楚,Map 的键值对是一个 Map.Entry 对象。
Student student1 = new Student("张三", 23);
Student student2 = new Student("李四", 24);

Map<Student> stuMap = new HashMap<>();
stuMap.put("student1", student1);
stuMap.put("student2", student2);

model.addAttribute("stuMap", stuMap);
           
<p th:each="entry : ${stuMap}">
	<!-- 状态对象为当前遍历对象加Stat后缀 -->
	<span th:text="${entryStat.index}"><span>
	<span th:text="${entry.key}"><span>
	<span th:text="${entry.value}"><span>
	<span th:text="${entry.value.name}"><span>
	<span th:text="${entry.value.age}"><span>
</p>
           

html标签相关

th:text/th:utext

  • 这两个属性均用于在标签体中显示动态文本。但不同的是,th:utext 会解析文本中的HTML 标签,而 th:text 则是原样显示。
<div th:text="${welcome}"></div>
<hr>
<div th:utext="${welcome}"></div>
           

th:name…th:value

  • 该属性用于获取标签动态 name 属性值,及标签的默认 value 值。

URL路径相关

  • th:action、th:src、th:href,这三个都是与 URL 路径相关的属性。若这些 URL 中包含有动态参数,则它们的值需要 URL 表达式@{…}与变量表达式${…}配合使用。下面以<img/>标签中的 th:src 为例演示用法。

css/js相关

th:id/th:name

  • 这两个属性可以获取标签的动态 id 与 name 属性,以便在 js 中使用。

th:style

  • 该属性用于获取标签的 css 动态样式。

th:onclick

  • 该属性用于获取标签的单击事件所触发的动态事件,即单击事件所触发的方法名。这些 js 事件属性很多,都是以 th:on 开头。
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

内联属性th:inline

  • 其应用场景是,在 HTML 某标签显示文本内部存在部分数据来自于动态数据,或 JS 内部需要使用动态数据的场景。在该场景中,可以使用[[ . . . ] ] 或 [ ( {...}]]或[( ...]]或[({…})]的方式将动态数据嵌入到指定的文本或脚本内部。
  • th:inline 的取值有四个:text, javascript、css 和 non。分别表示内联文本、内联脚本、内联 css,与禁止内联,即不解析[[${…}]]。不过,th:inline=”text”可以省略不写。

内联文本

<p th:inline="text">
	他的名字是:[[${student.name}]]
</p>
<!-- 该方式会正确显示,th:inline="text"可以省略 -->
<p>
	我的名字是:[[${student.name}]]
</p>
           

内联脚本

<!-- th:inline="javascript"不可省略 -->
<script th:inline="javascript" type="text/javascript">
	// 无法获取
	// alert(${student.name});
	// 正常显示
	alert([[${student.name}]]);
</script>
           

内联CSS

model.addAttribute("elementId", "reddiv");
model.addAttribute("bgColor", "red");
           
<div id="reddiv">
	我的背景要变为红色
</div>
<style th:inline="css">
	#[[${elementId}]] {
		width: 100px;
		height: 100px;
		background: [[${bgColor}]];
	}
</style>
           

万能属性th:attr

  • 该标签只所以称为万能属性,其主要具有两个应用场景,这两个场景在官方文档中均有详细讲解。

为无定义的属性赋予动态参数

  • 很多 HTML 标签的属性都有其对应的 Thymeleaf 的 th 命名空间中属性,但并不是所有的都存在对应属性。若没有其对应的 th 命名空属性,但又想让其获取动态值,就需要使用该属性了。
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

一次为多个属性赋予动态参数

  • 若想一次为多个属性赋予动态参数,则可以使用该属性。
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

Thymeleaf运算基础

Thymeleaf字面量

  • 字面量,即字面常量。Thymeleaf 中有四种字面量:文本、数字、布尔,及 null。

文本字面量

  • 由单引号括起来的字符串,称为文本字面量。
<div> 
	我爱你,<span th:text="'老婆'"></span>
</div>
           

数字字面量

  • 数字字面量就是数字,可以是整数,也可以是小数。
<div> 
	3.14 + 6 = <span th:text="3.14 + 6"></span>
</div>
           

布尔字面量

  • 布尔字面量就是 true、false,也可以写为 TRUE、FALSE、True、False。
<div> 
	<span th:if="${isClose} == false">欢迎光临</span>
	<span th:if="${isClose} == true">关门歇业</span>
	<span th:if="${isClose} == FALSE">欢迎光临</span>
	<span th:if="${isClose} == TRUE">关门歇业</span>
	<span th:if="${isClose} == False">欢迎光临</span>
	<span th:if="${isClose} == True">关门歇业</span>
</div>
           

null字面量

  • 表示空,其一般用于判断。若对象未定义,或对象已定义但其值为 null,则为 null 的判断结果为 true;若集合不为 null,但长度为 0,则为 null 的判断结果为 false。
Student stu = null;
model.addAttribute("stu", stu);

List<String> cities = new ArrayList<>();
model.addAttribute("cities", cities);
           
<div> 
	<span th:if="${user} == null">对象未定义</span>
	<span th:if="${stu} == null">学生为空</span>
	<span th:if="${cities} != null">集合长度为0,但不为null</span>
</div>
           

Thymeleaf运算符

字符串拼接运算符

  • 可以使用加号(+)进行字符串拼接,也可以将文本字面量与动态数据直接写入由双竖线括起来的字符串内,此时无需使用加号进行连接。

算术运算符

+ , - , * , / , %,但不支持++与--运算。
           

关系运算符

  • 以下两种写法均支持:
> , < , >= , <= , == , !=
gt , lt , ge , le , eq , ne
           

逻辑运算符

非:not 或者 ! 
与:and
或:or
           

条件运算符

? :
<!-- 以下两种写法均可 -->
<div th:text="${gender} == 'male' ? '男' : '女'"></div>
<div th:text="${gender == 'male'} ? '男' : '女'"></div>
           

Thymeleaf内置对象

  • 为了方便使用,Thymeleaf 中内置了很多对象,程序员可以直接使用。

Servlet API对象

  • 通过#reqest、#session、#servletContext 可以获取到 HttpServletRequest、HttpSession 及ServletContext 对象,然后就可以调用其相应的方法了。
@RequestMapping("/test/attr")
public Strng attrHandle(HttpServletRequest request, HttpSession session) {
	request.setAttribute("req", "reqValue");
	session.setAttribute("ses", "resValue");
	session.getServletContext().setAttribute("app", "appValue");
	return "index";
}
           
<!-- 获取域属性对象 -->
<span th:text="${#request.getAttribute('req')}"></span> <br>
<span th:text="${#session.getAttribute('res')}"></span> <br>
<span th:text="${#servletContext.getAttribute('app')}"></span> <br>
<!-- 获取上下文路径 -->
<span th:text="${#request.getContextPath()}"></span> <br>
<!-- 获取请求参数 -->
<span th:text="${#request.getParameter('name')}"></span> <br>
           

表达式实用对象

  • Tymeleaf 提供了大量的表达式实用对象,这些对象中存在大量的方法。这些方法直接使用“#工具对象.方法”的方式使用。其使用方式类似于 Java 中的静态方法。这些工具对象相关文档在官网文档的第 19 条中。
JavaEE 企业级分布式高级架构师(十一)Spring Boot学习笔记(1)Spring Boot基础模板引擎Thymeleaf

工具对象简介

  • 这些工具对象都是以#开头,由于是对象,所以首字母是小写,且一般都是复数形式,即一般都是以 s 结尾。
    • #executionInfo:获取当前Thymeleaf模板对象的执行信息。
    • #messages:获取外部信息。
    • #uris/#urls:URI/URL处理工具。
    • #conversions:类型转换工具。
    • #dates:日期处理工具。
    • #calendars:日历处理工具。
    • #numbers:数字处理工具。
    • #strings:字符串处理工具。
    • #Objects:对象处理工具。
    • #booleans:布尔值处理工具。
    • #arrays:数组处理工具。
    • #lists:List处理工具。
    • #sets:Set处理工具。
    • #maps:Map处理工具。
    • #aggregates:聚合处理工具,例如,对数组、集合进行求和、平均值等。
    • #ids:th:id属性处理工具。

应用举例

@RequestMapping("/test/util")
public Strng utilHandle(Model model) {
	int[] nums = {1, 2, 3, 4, 5};
	model.addAttribute("nums", nums);
	model.addAttribute("today", new Date());
	model.addAttribute("cardId", "325523200106256537");
	return "index";
}
           
<!-- 格式化日期 -->
<span th:text="${#dates.format(today, 'yyyy-MM-dd')}"> <br>
<!-- 从身份证中截取生日 -->
<span th:text="${#strings.substring(cardId, 6, 14)}"> <br>
<!-- 对数组元素求和 -->
<span th:text="${#aggregates.sum(nums)}"> <br>
           

继续阅读