SpringBoot-07-Thymeleaf模板引擎

SpringBoot-07-Thymeleaf模板引擎

1. 模板引擎

  • 前端交给我们的页面,是html页面。如果是以前开发,需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,可以用jsp轻松实现数据的显示,及交互等。
  • jsp支持非常强大的功能,包括能写Java代码。
    • 但是我们现在的情况是,SpringBoot首先是以jar包的方式,不是war
    • 第二,我们用的是内嵌的Tomcat容器,它现在默认是不支持jsp的。
  • 那不支持jsp,如果直接用纯静态页面的方式,那给开发会带来非常大的麻烦,那怎么办呢?
  • 注意:一体式的开发才会用到thymeleaf
    • 在前后端分离的项目中,其实还是用vue,react

SpringBoot推荐你可以来使用模板引擎:

  • 模板引擎,其实大家听到很多,其实jsp就是一个模板引擎,还有用的比较多的freemarker,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的
  • 模板引擎的作用就是我们来写一个页面模板,比如其中有些值是动态的,就要写一些表达式。
    • 而这些值从哪里来,是从后台封装的一些数据,然后把这个模板和这个数据交给模板引擎,模板引擎按照我们的这个数据把这表达式解析,填充到指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写进去,这就是我们的模板引擎。
  • 只不过呢,就是说不同模板引擎之间,他们可能这个语法有点不一样。

2. 引入 Thymeleaf

1
2
3
4
5
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • Maven会自动下载对应的包

3. Thymeleaf 原理分析

  • 前面呢,已经引入了Thymeleaf,那这个要怎么使用呢?

  • 首先得按照SpringBoot的自动配置原理看一下我们这个Thymeleaf的自动配置规则,在按照那个规则,我们进行使用。

去找一下Thymeleaf的自动配置类:ThymeleafProperties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
// 前缀,后缀,视图编码
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";

private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";
private Charset encoding;
}

可以看到其中的前缀和后缀!
我们要做的只需要 把html页面放在类路径下的templates文件夹下,thymeleaf就可以帮我们自动渲染!
  • 使用thymeleaf什么都不需要配置,只需要将他放在指定的文件夹下即可!
  • 注意:⚠️
    • 如果是Springboot 2.1.x的,导入的Thymeleaf是 2.x版本
    • 这可能会导致错误的发生

4. Thymeleaf 简单使用

  1. 编写一个TestController
1
2
3
4
5
6
7
8
9
@Controller
public class TestController {
// 视图跳转的拼接
@RequestMapping("/t1")
public String test1(){
//classpath:/templates/test.html
return "test";
}
}
  1. 编写一个test.html页面放在templates目录下:
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>测试页面</h1>

</body>
</html>
  1. 启动项目请求测试

5. Thymeleaf 语法

  • 要学习语法,还是参考官网文档最为准确,我们找到对应的版本看一下;

  • Thymeleaf官网:https://www.thymeleaf.org/

做个最简单的练习 :我们需要查出一些数据,在页面中展示

  1. controller中增加数据传输
1
2
3
4
5
6
//结论:只要需要使用thymeleaf,只需要导入对应的依赖就可以了
@RequestMapping("test")
public String test(Model model){
model.addAttribute("msg","<h1>helloSpringBoot</h1>");
model.addAttribute("users", Arrays.asList("zhuuu","朱酱酱"));
return "test";
  1. 要使用thymeleaf,需要在html文件中导入命名空间的约束,方便提示。可以去官方文档中看一下命名空间拿来过来:
1
xmlns:th="http://www.thymeleaf.org"
  1. 编写前端页面(.html)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<!--所有的html元素都可以被thymeleaf接管 th:元素名-->
<div th:text="${msg}"></div> // 这个没有被专义
<div th:utext="${msg}"></div> // 下面被转义了

<hr>

<h3 th:each="user:${users}" th:text="${user}"></h3>

</body>
</html>


OK,入门搞定,来认真研习一下Thymeleaf的使用语法!

1、可以使用任意的 th:attr 来替换Html中原生属性的值!

2、能写哪些表达式呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Simple expressions:(表达式语法)
Variable Expressions: ${...}:获取变量值;OGNL;
1)、获取对象的属性、调用方法
2)、使用内置的基本对象:#18
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.

3)、内置的一些工具对象:
      #execInfo : information about the template being processed.
      #uris : methods for escaping parts of URLs/URIs
      #conversions : methods for executing the configured conversion service (if any).
      #dates : methods for java.util.Date objects: formatting, component extraction, etc.
      #calendars : analogous to #dates , but for java.util.Calendar objects.
      #numbers : methods for formatting numeric objects.
      #strings : methods for String objects: contains, startsWith, prepending/appending, etc.
      #objects : methods for objects in general.
      #bools : methods for boolean evaluation.
      #arrays : methods for arrays.
      #lists : methods for lists.
      #sets : methods for sets.
      #maps : methods for maps.
      #aggregates : methods for creating aggregates on arrays or collections.
==================================================================================

Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
Message Expressions: #{...}:获取国际化内容
Link URL Expressions: @{...}:定义URL;
Fragment Expressions: ~{...}:片段引用表达式

Literals(字面量)
Text literals: 'one text' , 'Another one!' ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,…

Text operations:(文本操作)
String concatenation: +
Literal substitutions: |The name is ${name}|

Arithmetic operations:(数学运算)
Binary operators: + , - , * , / , %
Minus sign (unary operator): -

Boolean operations:(布尔运算)
Binary operators: and , or
Boolean negation (unary operator): ! , not

Comparisons and equality:(比较运算)
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )

Conditional operators:条件运算(三元运算符)
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)

Special tokens:
No-Operation: _
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信