【WEEK9】 【DAY7】Thymeleaf模板引擎【中文版】

2024.4.28 Sunday

8.Thymeleaf模板引擎

8.1.模板引擎

前端交给我们的页面,是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等。
jsp支持非常强大的功能,包括能写Java代码,但是呢,我们现在的这种情况,SpringBoot这个项目首先是以jar的方式,不是war,像第二,我们用的还是嵌入式的Tomcat,所以呢,现在默认是不支持jsp的
那不支持jsp,如果我们直接用纯静态页面的方式,那给我们开发会带来非常大的麻烦,那怎么办呢?
SpringBoot推荐你可以来使用模板引擎:
模板引擎,我们其实大家听到很多,其实jsp就是一个模板引擎,还有用的比较多的freemarker,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的,什么样一个思想呢?我们来看一下这张图:
在这里插入图片描述
模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过呢,就是说不同模板引擎之间,他们可能这个语法有点不一样。其他的我就不介绍了,我主要来介绍一下SpringBoot给我们推荐的Thymeleaf模板引擎,这模板引擎呢,是一个高级语言的模板引擎,他的这个语法更简单。而且呢,功能更强大。
我们呢,就来看一下这个模板引擎,那既然要看这个模板引擎。首先,我们来看SpringBoot里边怎么用。

8.2.引入Thymeleaf

8.2.1.怎么引入

对于springboot来说,什么事情不都是一个start的事情嘛,我们去在项目中引入一下。参考以下三个网址:

8.2.2.Thymeleaf 官网

https://www.thymeleaf.org/

8.2.3.Thymeleaf 在Github 的主页

https://github.com/thymeleaf/thymeleaf

8.2.4.Spring官方文档:找到对应的版本

https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter

8.2.5.找到对应的pom依赖:可以适当点进源码看下本来的包!

在pom.xml的dependencies中删除webjars依赖,导入thymeleaf依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.7.13</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.example</groupId>
   <artifactId>springboot-03-web2</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>springboot-03-web2</name>
   <description>springboot-03-web2</description>
   <properties>
      <java.version>8</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

      <!--thymeleaf-->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

在这里插入图片描述

8.2.6.删除index.html

8.2.7.搜索(shift双击)进入thymeleafProperties.java

发现public static final String DEFAULT_PREFIX = “classpath:/templates/”;和public static final String DEFAULT_SUFFIX = “.html”;所以在resources文件夹下的templates文件夹中编辑一个后缀为html的文件,thymeleaf会进行自动渲染。
【约定大于配置】

8.2.8.新建IndexController.java

在这里插入图片描述

package com.P14.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
    @RequestMapping("/testtemplates")
    public String test(){
        //classpath:/templates/test.html
        return "test";
    }
}

8.2.9.新建test.html

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

8.2.10.重启并运行

http://localhost:8080/testtemplates
在这里插入图片描述

8.3.Thymeleaf语法学习

8.3.1.下载官方文档

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
我们做个最简单的练习:我们需要查出一些数据,在页面中展示

8.3.2.修改测试请求,增加数据传输

8.3.2.1.修改IndexController.java
package com.P14.controller;

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

@Controller
public class IndexController {
    @RequestMapping("/testtemplates")
    public String test(Model model){
        //存入数据
        model.addAttribute("message","Hello,Thymeleaf");
        //classpath:/templates/test.html
        return "test";
    }
}
8.3.2.2.修改test.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!--导入命名空间的约束xmlns:th="http://www.thymeleaf.org"可从官方文档P11找到-->
<!--Standard Expression Syntax等内容见P17-->
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--所有的html元素都可以被thymeleaf替换接管: th:元素名-->
<div th:text="${message}"></div>
<!--使用<h1>${message}</h1>无法识别,就直接打印出${message}-->
</body>
</html>

8.3.3.重启并测试

http://localhost:8080/testtemplates
在这里插入图片描述

8.3.4.Thymeleaf语法

8.3.4.1.我们可以使用任意的th:attr来替换html中原生属性的值
8.3.4.2.能写哪些表达式?
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: _
8.3.4.3.练习测试
8.3.4.3.1.修改IndexController.java
package com.P14.controller;

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

import java.lang.reflect.Array;
import java.util.Arrays;

@Controller
public class IndexController {
    @RequestMapping("/testtemplates")
    public String test(Model model){
        //存入数据
        //注:不被转义就是字符串,转义了才是页面
        model.addAttribute("message","<h1>hello,springboot</h1>");
        //一个集合两个元素,如何遍历
        model.addAttribute("users", Arrays.asList("zhangsan","lisi"));
        //classpath:/templates/test.html
        return "test";
    }
}
8.3.4.3.2.修改test.html
<!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="${message}"></div>
<!--不转义-->
<div th:utext="${message}"></div>

<hr><!--生成分隔的长横线-->
<!--遍历数据-->
<h3 th:each="user:${users}" th:text="${user}"></h3>
<hr>
<h3 th:each="user:${users}">[[ ${user} ]]</h3>
<!--以上两行等效,推荐使用第一种(CH9),不建议使用行内写法(位于文档CH12)-->

</body>
</html>
8.3.4.3.3.重启并测试

在这里插入图片描述

  • 61
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值