10、框架-SpringBoot-模板引擎Thymeleaf

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_40871734/article/details/100009710

模板引擎

前端交给我们的页面,是html页面。如果是以前开发,我们需要把他们转成jsp页面,jsp好处就是当查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等。jsp支持非常强大的功能,包括能写Java代码,但是现在这种情况,首先SpringBoot这个项目是以jar的方式,不是war,第二,我们用的还是嵌入式的Tomcat,所以它现在默认是不支持jsp的。

不支持jsp,如果直接用纯静态页面的方式,会给我们开发会带来非常大的麻烦,那怎么办呢,SpringBoot推荐你可以来使用模板引擎。

模板引擎有非常多,jsp其实就是一个模板引擎,还有用的比较多的freemarker,包括SpringBoot给我们推荐的Thymeleaf,再多的模板引擎,它们的思想都是一样的,来看一下这张图。
在这里插入图片描述
模板引擎的作用就是我们来写一个页面模板,比如有些值是动态的,我们写一些表达式,而这些值从哪来呢,我们来组装一些数据,把这些数据找到。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容写出去,这就是模板引擎。不管是jsp还是其他模板引擎都是这个思想。只是不同模板引擎之间,它们的语法有点不一样。SpringBoot给我们推荐的Thymeleaf模板引擎,是一个高级语言的模板引擎,它的语法更简单,功能更强大。

我们来看一下这个模板引擎在SpringBoot里边怎么用。

第一步:在项目中引入thymeleaf,给大家三个网址:

1、Thymeleaf 官网:https://www.thymeleaf.org/

2、Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf

3、Spring官方文档:“https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/htmlsingle/#using-boot-starter” , 找到我们对应的版本

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

maven会自动下载jar包
在这里插入图片描述

使用Thymeleaf

我们已经引入了Thymeleaf,那这个要怎么使用呢?

首先得按照SpringBoot的自动配置原理看一下Thymeleaf的自动配置规则,再按照规则进行使用。

去找一下Thymeleaf的自动配置类;
在这里插入图片描述
这个包下有我们的thymeleaf,看配置类,选择部分

@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就可以帮我们自动渲染了。

可以去测试一下 , 写一个Controller,跳转到一个指定页面,这个指定页面需要在 类路径下的模板目录下

使用thymeleaf什么都不需要配置,只需要将它放在指定的文件夹下即可

Thymeleaf语法

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

Thymeleaf 官网:https://www.thymeleaf.org/ , 简单看一下官网!我们去下载Thymeleaf的官方文档!

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

在controller编写一个请求,放进去一些数据;

@RequestMapping("/success")
    public String success(Model model){
        //存入数据
        model.addAttribute("msg","Hello,Thymeleaf");
        //classpath:/templates/success.html
        return "success";
    }

要使用thymeleaf,需要在html文件中导入命名空间的约束,方便提示。去官方文档的#3中看一下命名空间拿来过来

 xmlns:th="http://www.thymeleaf.org"

编写前端页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
   <meta charset="UTF-8">
   <title>Thymeleaf</title>
</head>
<body>
<h1>Success</h1>

<!--th:text就是将div中的内容设置为它指定的值,和之前学习的Vue一样-->
<div th:text="${msg}"></div>
</body>
</html>

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

一、可以使用任意的 th:attr 来替换Html中原生属性的值, 全部属性可以参考官网

文档#10:th语法
在这里插入图片描述
二、能写那些表达式?可以看到官方文档 #4

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.
                
                ${session.foo}
      3)、内置的一些工具对象:
      #execInfo : information about the template being processed.
      #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
      #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.
      #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

==============================================================================================
Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
   补充:配合 th:object="${session.user}:

   <div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
    <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
    </div>
    
Message Expressions: #{...}:获取国际化内容
Link URL Expressions: @{...}:定义URL;
            @{/order/process(execId=${execId},execType='FAST')}

Fragment Expressions: ~{...}:片段引用表达式
            <div th:insert="~{commons :: main}">...</div>
            
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: _ 

测试练习

编写一个Controller,放一些数据

 @RequestMapping("/success2")
   public String success2(Map<String,Object> map){
       //存入数据
       map.put("msg","<h1>Hello</h1>");
       map.put("users", Arrays.asList("qinjiang","kuangshen"));
       //classpath:/templates/success.html
       return "success";
   }

前端

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>狂神说</title>
</head>
<body>
<h1>Success</h1>

<div th:text="${msg}"></div>
<!--不转义-->
<div th:utext="${msg}"></div>

<!--遍历数据-->
<!--th:each每次遍历都会生成当前这个标签:官网#9-->
<h4 th:each="user :${users}" th:text="${user}"></h4>

<h4>
    <!--行内写法:官网#12-->
    <span th:each="user:${users}">[[${user}]]</span>
</h4>

</body>
</html>

很多样式,即使现在学习了也会忘记,所以在学习过程中需要使用什么,根据官方文档来查询才是最重要的,要熟练使用官方文档

猜你喜欢

转载自blog.csdn.net/qq_40871734/article/details/100009710