springboot之Thymeleaf模板引擎

什么是模板引擎

前端交给我们的页面,是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等

jsp支持非常强大的功能,包括能写Java代码,但是SpringBoot这个项目首先是以jar的方式,不是war,而且我们用的还是嵌入式的Tomcat,所以现在默认是不支持jsp的模板引擎的

因此我们可以使用Thymeleaf模板引擎,springboot所支持的模板引擎有很多,模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过呢,就是说不同模板引擎之间,他们可能这个语法有点不一样,Thymeleaf模板引擎,是一个高级语言的模板引擎,他的这个语法更简单。功能更强大

如何使用Thymeleaf

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

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

Spring官方文档:https://docs.spring.io/spring-boot/docs/2.4.3/reference/htmlsingle/#using-boot-starter

添加对应的依赖,可以适当点进去源码看下本来的包


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

Maven会自动下载对应的依赖jar包,可以点进去看下载的内容

在这里插入图片描述

Thymeleaf模板引擎分析使用

  1. 先从springboot的自动配置类中寻找ThymeleafAutoConfiguration类
    在这里插入图片描述
    在这里插入图片描述

  2. 进入ThymeleafAutoConfiguration配置类后,找到能够配置属性的ThymeleafProperties类

在这里插入图片描述

  1. 可以看到,它和我们的application.properties/yaml配置文件绑定了相应的属性值,并且默认编码为utf-8,寻找资源的路径前缀为从"classpath:/templates/"寻找,后缀为.html的资源文件
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
	//默认编码为utf-8
	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
	//从"classpath:/templates/"寻找
	public static final String DEFAULT_PREFIX = "classpath:/templates/";
	//后缀为.html的资源文件
	public static final String DEFAULT_SUFFIX = ".html";

也就是说只需要把我们的html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了,使用thymeleaf什么都不需要配置,只需要将他放在指定的文件夹下即可

在这里插入图片描述

  1. 测试:编写一个Controller类
@Controller
public class ThymeleafController {

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

编写一个test.html页面放在templates目录下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Hello Thymeleaf</h1>
</body>
</html>
  1. 结果:
    在这里插入图片描述

Thymeleaf语法学习

  1. 从官网学习:

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

  1. 首先需要在html中引用约束(命名空间)
<html xmlns:th="http://www.thymeleaf.org">
  1. 我们写一个最简单的测试请求,增加数据传输

在这里插入图片描述
在这里插入图片描述

编写controller类:

@Controller
public class ThymeleafController {

    @RequestMapping("/test")
    public String test(Model model){
        //存入数据
        model.addAttribute("msg","你好呀!");
        //"classpath:templates/test.html"
        return "test";
    }
}

编写前端页面并取值:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text就是将div中的内容设置为它指定的值-->
<!--${属性名}表达式语法用来获取属性或变量的值-->
    <h1 th:text="${msg}"></h1>
</body>
</html>

结果:
在这里插入图片描述

一些属性语法:

在这里插入图片描述

常见表达式:


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

简单测试:

编写controller类:

@Controller
public class ThymeleafController {

    @RequestMapping("/test")
    public String test(Model model){
        //存入数据
        model.addAttribute("msg","<h1>你好呀!</h1>");
        model.addAttribute("lists", Arrays.asList("陈晖","chenhui","22"));
        //"classpath:templates/test.html"
        return "test";
    }
}

编写test.html页面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text就是将div中的内容设置为它指定的值-->
<!--${属性名}表达式语法用来获取属性或变量的值-->
<!--转义-->
    <div th:text="${msg}"></div>
<!--不转义,会被解析成HTML-->
    <div th:utext="${msg}"></div>

    <hr>
<!--遍历数据-->
<!--th:each每次遍历都会生成当前这个标签-->
    <div th:each="list:${lists}" th:text="${list}"></div>

    <hr>
<!--行内写法-->
    <div th:each="list:${lists}">[[${list}]]</div>
</body>
</html>

结果:
在这里插入图片描述
注意如果没有任何配置thymeleaf, 页面要在templates下面,使用thymeleaf时需要经过controller跳转才能访问 直接访问templates下面的html页面会报 404 或 500

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值