Spring Boot——整合 Thymeleaf模板引擎

1,236 阅读4分钟

Spring Boot——Thymeleaf模板引擎

1、什么是Thymeleaf

Thymeleaf是一个XML/XHTML/HTML5模板引擎,==可用于Web与非Web环境中的应用开发,可以作为mvc的web应用的view层==。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。

Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP,或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。 在这里插入图片描述

2、什么是模板引擎

模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。

Thymeleaf 是一个服务器端 Java 模板引擎,能够处理 HTML、XML、CSS、JAVASCRIPT 等模板文件。Thymeleaf 模板可以直接当作静态原型来使用,它主要目标是为开发者的开发工作流程带来优雅的自然模板,也是 Java 服务器端 HTML5 开发的理想选择。

从字面上理解模板引擎,最重要的就是模板二字,这个意思就是做好一个模板后套入对应位置的数据,最终以html的格式展示出来,这就是模板引擎的作用。

模板引擎的思想: 在这里插入图片描述

模板引擎就是我们用来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式可以取出来。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。

3、Thymeleaf的简单测试

Thymeleaf官网

Thymeleaf 在GitHub主页

springboot文档

步骤:

1、引入Thymeleaf依赖

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

查看下载好的jar包,我们开发的时候要使用3.0.x版本的

在这里插入图片描述

2、编写控制器和页面

@Controller
public class HelloController {
    @RequestMapping("/h1")
    public String hello(){
        return "test";
    }
}

页面放在templates目录下,注意:templates目录下的页面只能通过controller访问

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

启动springboot应用程序测试。成功跳转!这个测试只是简单是实现页面跳转,没有规范的使用Thymeleaf。

4、Thymeleaf语法使用

4.1、命名空间

通过<html xmlns:th="http://www.thymeleaf.org">引入 Thymeleaf 命名空间。

4.2、简单表达式

语法名称描述作用
${…}Variable Expressions变量表达式取出上下文变量的值
*{…}Selection Variable Expressions选择变量表达式取出选择的对象的属性值
#{…}Message Expressions消息表达式使文字消息国际化,I18N
@{…}Link URL Expressions链接表达式用于表示各种超链接地址
~{…}Fragment Expressions片段表达式引用一段公共的代码片段

${…}测试:

    @RequestMapping("/h1")
    public String hello(Model model){
        model.addAttribute("msg","<h1>hello,Spring Boot</h1>");
        return "test";
    }
<!DOCTYPE html>
<!--引入 Thymeleaf 命名空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--所有的html元素都可以被Thymeleaf替换、接管,只要被接管了,就可以使用Thymeleaf表达式。
接管方式:th:元素名,如 th:class="" th:id=""
-->
<h1>
    <p th:text="${msg}"></p><!--转义-->
    <p th:utext="${msg}"></p><!--不转义-->
</h1>
</body>
</html>

启动springboot应用程序测试,上面的把h1标签转义了,下面的没有

在这里插入图片描述

测试th:each

    @RequestMapping("/h1")
    public String hello(Model model) {
        model.addAttribute("users", Arrays.asList("万里","桃仙"));
        return "test";
    }
<!DOCTYPE html>
<!--引入 Thymeleaf 命名空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--users遍历出来的每个值叫做user, 把user取出来-->
<p th:each="user:${users}" th:text="${user}"></p>
    
<!--行内写法,效果一样-->
<span th:each="user:${users}">[[${user}]]</span>
    
</h1>
</body>
</html>

启动springboot应用程序测试,成功把值遍历出来!

在这里插入图片描述

Thymeleaf的表达式语法:

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

我们在学习过程中,需要使用什么,根据官方文档来查询,才是最重要的,要熟练使用官方文档:

Thymeleaf文本文档

Thymeleaf中文文本文档