springboot学习之Thymeleaf模板引擎及原理介绍

 更新时间:2022年2月24日 14:21  点击:235 作者:我是坑货

模板引擎

springboot我们目前是以jar包的形式打包,实际上我们之前是打成war包,放到tomcat服务器里面,可以用JSP。
但是jar包就导致不能用JSP,换一种方式就是springboot推荐的Thymeleaf模板引擎(JSP也是一种模板引擎,除此之外还有什么framework也是一种模板引擎),

什么是模板引擎?

模板引擎就是解决我们需要动态赋值给前端的一种解决方案
(模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过呢,就是说不同模板引擎之间,他们可能这个语法有点不一样。其他的我就不介绍了,我主要来介绍一下SpringBoot给我们推荐的Thymeleaf模板引擎,这模板引擎呢,是一个高级语言的模板引擎,他的这个语法更简单。而且呢,功能更强大。)

模板引擎的原理

引入Thymeleaf

引入就是导入依赖,以下是网址是相关的地址
Thymeleaf 官网:https://www.thymeleaf.org/

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

Spring官方文档:找到我们对应的版本

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

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

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

Thymeleaf分析

Thymeleaf的引入依赖文件ThymeleafProperties,文件内容如下:

  // IntelliJ API Decompiler stub source generated from a class file
  // Implementation of methods is not available
package org.springframework.boot.autoconfigure.thymeleaf;
@org.springframework.boot.context.properties.ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
    private static final java.nio.charset.Charset DEFAULT_ENCODING;
    public static final java.lang.String DEFAULT_PREFIX = "classpath:/templates/";
    public static final java.lang.String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate;
    private boolean checkTemplateLocation;
    private java.lang.String prefix;
    private java.lang.String suffix;
    private java.lang.String mode;
    private java.nio.charset.Charset encoding;
    private boolean cache;
    private java.lang.Integer templateResolverOrder;
    private java.lang.String[] viewNames;
    private java.lang.String[] excludedViewNames;
    private boolean enableSpringElCompiler;
    private boolean renderHiddenMarkersBeforeCheckboxes;
    private boolean enabled;
    private final org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties.Servlet servlet;
    private final org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties.Reactive reactive;
    public ThymeleafProperties() { /* compiled code */ }
    public boolean isEnabled() { /* compiled code */ }
    public void setEnabled(boolean enabled) { /* compiled code */ }
    public boolean isCheckTemplate() { /* compiled code */ }
    public void setCheckTemplate(boolean checkTemplate) { /* compiled code */ }
    public boolean isCheckTemplateLocation() { /* compiled code */ }
    public void setCheckTemplateLocation(boolean checkTemplateLocation) { /* compiled code */ }
    public java.lang.String getPrefix() { /* compiled code */ }
    public void setPrefix(java.lang.String prefix) { /* compiled code */ }
    public java.lang.String getSuffix() { /* compiled code */ }
    public void setSuffix(java.lang.String suffix) { /* compiled code */ }
    public java.lang.String getMode() { /* compiled code */ }
    public void setMode(java.lang.String mode) { /* compiled code */ }
    public java.nio.charset.Charset getEncoding() { /* compiled code */ }
    public void setEncoding(java.nio.charset.Charset encoding) { /* compiled code */ }
    public boolean isCache() { /* compiled code */ }
    public void setCache(boolean cache) { /* compiled code */ }
    public java.lang.Integer getTemplateResolverOrder() { /* compiled code */ }
    public void setTemplateResolverOrder(java.lang.Integer templateResolverOrder) { /* compiled code */ }
    public java.lang.String[] getExcludedViewNames() { /* compiled code */ }
    public void setExcludedViewNames(java.lang.String[] excludedViewNames) { /* compiled code */ }
    public java.lang.String[] getViewNames() { /* compiled code */ }
    public void setViewNames(java.lang.String[] viewNames) { /* compiled code */ }
    public boolean isEnableSpringElCompiler() { /* compiled code */ }
    public void setEnableSpringElCompiler(boolean enableSpringElCompiler) { /* compiled code */ }
    public boolean isRenderHiddenMarkersBeforeCheckboxes() { /* compiled code */ }
    public void setRenderHiddenMarkersBeforeCheckboxes(boolean renderHiddenMarkersBeforeCheckboxes) { /* compiled code */ }
    public org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties.Reactive getReactive() { /* compiled code */ }
    public org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties.Servlet getServlet() { /* compiled code */ }
    public static class Reactive {
        private org.springframework.util.unit.DataSize maxChunkSize;
        private java.util.List<org.springframework.http.MediaType> mediaTypes;
        private java.lang.String[] fullModeViewNames;
        private java.lang.String[] chunkedModeViewNames;
        public Reactive() { /* compiled code */ }
        public java.util.List<org.springframework.http.MediaType> getMediaTypes() { /* compiled code */ }
        public void setMediaTypes(java.util.List<org.springframework.http.MediaType> mediaTypes) { /* compiled code */ }
        public org.springframework.util.unit.DataSize getMaxChunkSize() { /* compiled code */ }
        public void setMaxChunkSize(org.springframework.util.unit.DataSize maxChunkSize) { /* compiled code */ }
        public java.lang.String[] getFullModeViewNames() { /* compiled code */ }
        public void setFullModeViewNames(java.lang.String[] fullModeViewNames) { /* compiled code */ }
        public java.lang.String[] getChunkedModeViewNames() { /* compiled code */ }
        public void setChunkedModeViewNames(java.lang.String[] chunkedModeViewNames) { /* compiled code */ }
    }
    public static class Servlet {
        private org.springframework.util.MimeType contentType;
        private boolean producePartialOutputWhileProcessing;
        public Servlet() { /* compiled code */ }
        public org.springframework.util.MimeType getContentType() { /* compiled code */ }
        public void setContentType(org.springframework.util.MimeType contentType) { /* compiled code */ }
        public boolean isProducePartialOutputWhileProcessing() { /* compiled code */ }
        public void setProducePartialOutputWhileProcessing(boolean producePartialOutputWhileProcessing) { /* compiled code */ }
}

我们可以在其中看到默认的前缀和后缀。
我们只需要把我们的html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了。

启动访问结果

Thymeleaf 语法学习

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

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

做一个最简单的向页面传值操作
(1)写一个页面,一个msg来作为传值

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>ZP</title>
</head>
<body>
<h1>测试页面</h1>

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

代码
注意这里return的字符串要和上面的templates下面的html文件名字相同。

package com.example.zpspringboot3.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * @Author: zhangpeng
 * @Date: 2022/2/21 16:02
 */
@Controller
public class TestController {
//    @RequestMapping("/t1")
//    public String test1(){
//        //classpath:/templates/test.html
//        return "text";
//    }
    @RequestMapping("/t1")
    public String test1(Model model){
        //存入数据
        model.addAttribute("msg","Hello,Thymeleaf");
        //classpath:/templates/test.html
        return "text2";
    }
}

测试

通过thymeleaf官网文档学习一些语法:
1、我们可以使用任意的 th:attr 来替换Html中原生属性的值!

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

练习测试:

1、 我们编写一个Controller,放一些数据

 @RequestMapping("/t2")
    public String test2(Map<String,Object> map){
        //存入数据
        map.put("msg","<h1>Hello</h1>");
        map.put("users", Arrays.asList("zp","zhangpeng"));
        //classpath:/templates/test.html
        return "text3";
    }

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>狂神说</title>
</head>
<body>
<h1>测试页面</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>

到此这篇关于springboot学习Thymeleaf模板引擎的文章就介绍到这了,更多相关springboot Thymeleaf模板引擎内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/FeiChangWuRao/article/details/12304847

[!--infotagslink--]

相关文章

  • 解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题

    这篇文章主要介绍了解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-28
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • 详解springBoot启动时找不到或无法加载主类解决办法

    这篇文章主要介绍了详解springBoot启动时找不到或无法加载主类解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • SpringBoot集成Redis实现消息队列的方法

    这篇文章主要介绍了SpringBoot集成Redis实现消息队列的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10
  • 深入解析WordPress中加载模板的get_template_part函数

    这篇文章主要介绍了WordPress中加载模板的get_template_part函数,其中重点讲解了其函数钩子的使用,需要的朋友可以参考下...2016-01-14
  • 解决Springboot get请求是参数过长的情况

    这篇文章主要介绍了解决Springboot get请求是参数过长的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-17
  • Springboot+TCP监听服务器搭建过程图解

    这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
  • mysql配置模板(my-*.cnf)参数详细说明

    mysql安装成功后有几个默认的配置模板,列表如下: my-huge.cnf : 用于高端产品服务器,包括1到2GB RAM,主要运行mysql my-innodb-heavy-4G.ini : 用于只有innodb的安装,最多有4GB RAM,支持大的查询和低流量 my-large.cnf : 用于...2015-03-15
  • Spring Boot项目@RestController使用重定向redirect方式

    这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-02
  • springBoot 项目排除数据库启动方式

    这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
  • JavaScript模版引擎的基本实现方法浅析

    这篇文章主要介绍了JavaScript模版引擎的基本实现方法,讲解利用function对象来一步步编写简单的模板,需要的朋友可以参考下...2016-02-18
  • springboot中使用@Transactional注解事物不生效的坑

    这篇文章主要介绍了springboot中使用@Transactional注解事物不生效的原因,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-26
  • SpringBoot接口接收json参数解析

    这篇文章主要介绍了SpringBoot接口接收json参数解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-19
  • 详解SpringBoot之访问静态资源(webapp...)

    这篇文章主要介绍了详解SpringBoot之访问静态资源(webapp...),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-14
  • Smarty模板学习笔记之Smarty简介

    1、简介Smarty是一个使用PHP写出来的模板PHP模板引擎,是目前业界最著名的PHP模板引擎之一。它分离了逻辑代码和外在的内容,提供了一种易于管理和使用的方法,用来将原本与HTML代码混杂在一起PHP代码逻辑分离。简单的讲,目...2014-05-31
  • springboot多模块包扫描问题的解决方法

    这篇文章主要介绍了springboot多模块包扫描问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用详解

    这篇文章主要介绍了Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-11-18
  • 模板引擎smarty工作原理以及使用示例

    模板引擎是用于把模板文件和数据内容合并在一起的程序,便于网站开发有利于代码分离和维护,了解一个模板最好知道其工作原理,以便于实现一通万通。模板文件一般是HTML xml js等类型文件,如果不用模板引擎若要把数据显示在...2014-05-31
  • Ionic默认的Tabs模板使用实例

    这篇文章主要为大家详细介绍了Ionic默认的Tabs模板使用实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2016-09-01
  • Springboot实现多线程注入bean的工具类操作

    这篇文章主要介绍了Springboot实现多线程注入bean的工具类操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-27