SpringBoot之Thymeleaf模板引擎如何運用?案例詳解


 

SpringBoot之Thymeleaf模板引擎

根據B站狂神學java的筆記

模板引擎Thymeleaf

前端想要顯示數據,我們以前是把頁面轉換成jsp。這樣我們就能夠實現數據的顯示,及交互等。 jsp支持非常強大的功能,包括能寫Java代碼 。但是我們使用SpringBoot項目是jar方式而不是war。我們還是使用嵌入式的Tomcat,但現在springBoot默認是不支持jsp的。那該使用什么呢?
第二要注意光理論是不夠的。在此免費贈送5大JAVA架構項目實戰教程及大廠面試題庫,有興趣的可以進裙 783802103獲取,沒基礎勿進哦!

SpringBoot推薦你可以來使用模板引擎:

模板引擎,我們其實大家聽到很多,其實jsp就是一個模板引擎,還有用的比較多的freemarker,包括SpringBoot給我們推薦的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他們的思想都是一樣的,什么樣一個思想呢我們來看一下這張圖:

模板引擎的作用就是使用表達式解析后台的數據。

引入Thymeleaf

怎么引入呢,對於springboot來說,什么事情不都是一個start的事情嘛,我們去在項目中引入一下。給大家三個網址:

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依賴:可以適當點進源碼看下本來的包!

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
官網的jar包
<dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
       </dependency>

Thymeleaf分析

前面呢,我們已經引入了Thymeleaf,那這個要怎么使用呢?

我們首先得按照SpringBoot的自動配置原理看一下我們這個Thymeleaf的自動配置規則,在按照那個規則,我們進行使用。

我們去找一下Thymeleaf的自動配置類:ThymeleafProperties

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";

我們可以在其中看到默認的前綴和后綴!

我們只需要把我們的html頁面放在類路徑下的templates下,thymeleaf就可以幫我們自動渲染了。

使用thymeleaf什么都不需要配置,只需要將他放在指定的文件夾下即可!

測試

首先編寫一個TestController

@Controller
public class TestController {
    @RequestMapping("/test")
    public String test1(){
        //自動解析為classpath:/templates/test.html
        return "test";
    }
}

在template建立test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf測試頁面</title>
</head>
<body>
我進來了
</body>
</html>

運行測試:

thymeleaf語法

要學習語法,還是參考官網文檔最為准確,我們找到對應的版本看一下;

Thymeleaf 官網:https://www.thymeleaf.org/ , 簡單看一下官網!我們去下載Thymeleaf的官方文檔!

我們做個最簡單的練習 :我們需要查出一些數據,在頁面中展示

1.修改測試請求,增加數據傳輸

@Controller
public class TestController {
    @RequestMapping("/test")
    public String test1(Model model){
        //自動解析為classpath:/templates/test.html
        model.addAttribute("msg","hello Thymeleaf!");
        return "test";
    }
}

2.我們首先需要導入命名空間約束

我們可以去官方文檔的#3中看一下命名空間拿來過來:

<html lang="en"  xmlns:th="http://www.thymeleaf.org">

3.編寫頁面

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf測試頁面</title>
</head>
<body>
我進來了
<div th:text="${msg}"></div>
</body>
</html>

4.測試:

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

測試:

編寫controller

@Controller
public class TestController2 {
    @RequestMapping("/test1")
    public String test2(Map<String,Object> map){
        map.put("msg","<h1>Hello</h1>");
        map.put("users", Arrays.asList("qi","wuxin"));
        return "test";
    }
}

測試頁面

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf測試頁面</title>
</head>
<body>
我進來了
<!--轉義-->
<div th:text="${msg}"></div>
    <!--不轉義-->
<div th:utext="${msg}"></div>
<!--遍歷-->
<h4 th:each="user: ${users}" th:text="${user}"></h4>
<!--行內寫法-->
<h4 th:each="user: ${users}">[[${user}]]</h4>
</body>
</html>

結果頁面

最后注意:光理論是不夠的。在此免費贈送5大JAVA架構項目實戰教程及大廠面試題庫,有興趣的可以進裙 783802103獲取,沒基礎勿進哦!
本文的文字及圖片來源於網絡加上自己的想法,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM