整合營(yíng)銷(xiāo)服務(wù)商

          電腦端+手機(jī)端+微信端=數(shù)據(jù)同步管理

          免費(fèi)咨詢(xún)熱線(xiàn):

          SpringBoot系列-Thymeleaf模板

          SpringBoot系列-Thymeleaf模板

           前言

            thymeleaf是springboot官方推薦使用的java模板引擎,在springboot的參考指南里的第28.1.10 Template Engines中介紹并推薦使用thymeleaf,建議我們應(yīng)該避免使用jsp,jsp的本質(zhì)是一個(gè)java的servlet類(lèi),jsp引擎將jsp的內(nèi)容編譯成.class,"out.write"輸出到response再響應(yīng)到瀏覽器,雖然java是一次編譯,到處運(yùn)行,但也大大增加了服務(wù)器壓力,而且jsp將后臺(tái)java語(yǔ)言嵌入頁(yè)面,還要放入服務(wù)容器才能打開(kāi),前后端不分離,嚴(yán)重增加了前端工程師的開(kāi)發(fā)工作、效率。

            thymeleaf官網(wǎng)對(duì)thymeleaf的介紹:

            Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

            Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.

            With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.


            thymeleaf使用教程,騷操作:鼠標(biāo)右鍵,翻譯成簡(jiǎn)體中文再看。

            thymeleaf使用th屬性賦予每個(gè)標(biāo)簽與后臺(tái)交互的能力,當(dāng)html文件在本地直接用瀏覽器打開(kāi),瀏覽器引擎會(huì)忽略掉th屬性,并正常渲染頁(yè)面,當(dāng)把html文件放到服務(wù)容器訪問(wèn),th屬性與后臺(tái)交互,獲取數(shù)據(jù)替換原先的內(nèi)容,這樣前端工程師在編寫(xiě)html頁(yè)面時(shí),在本地開(kāi)發(fā),正常實(shí)現(xiàn)頁(yè)面邏輯效果即可,數(shù)據(jù)先寫(xiě)死,當(dāng)放到服務(wù)容器時(shí)數(shù)據(jù)從后臺(tái)獲取。


            spring對(duì)thymeleaf的配置,來(lái)自springboot參考手冊(cè),Common application properties:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#common-application-properties

          # THYMELEAF (ThymeleafAutoConfiguration)
          spring.thymeleaf.cache=true # Whether to enable template caching.
          spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it.
          spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists.
          spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks.
          spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions.
          spring.thymeleaf.encoding=UTF-8 # Template files encoding.
          spring.thymeleaf.excluded-view-names=# Comma-separated list of view names (patterns allowed) that should be excluded from resolution.
          spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
          spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
          spring.thymeleaf.reactive.chunked-mode-view-names=# Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set.
          spring.thymeleaf.reactive.full-mode-view-names=# Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set.
          spring.thymeleaf.reactive.max-chunk-size=0B # Maximum size of data buffers used for writing to the response.
          spring.thymeleaf.reactive.media-types=# Media types supported by the view technology.
          spring.thymeleaf.render-hidden-markers-before-checkboxes=false # Whether hidden form inputs acting as markers for checkboxes should be rendered before the checkbox element itself.
          spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
          spring.thymeleaf.servlet.produce-partial-output-while-processing=true # Whether Thymeleaf should start writing partial output as soon as possible or buffer until template processing is finished.
          spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
          spring.thymeleaf.template-resolver-order=# Order of the template resolver in the chain.
          spring.thymeleaf.view-names=# Comma-separated list of view names (patterns allowed) that can be resolved.


            使用

            maven引入依賴(lài)

                  <!--Thymeleaf模板依賴(lài)-->
                  <dependency>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-starter-thymeleaf</artifactId>
                  </dependency>


            項(xiàng)目結(jié)構(gòu)

            thymeleaf默認(rèn),頁(yè)面跳轉(zhuǎn)默認(rèn)路徑:src/main/resources/templates,靜態(tài)資源默認(rèn)路徑:src/main/resources/static;



            yml配置文件

            我們也可以在配置文件中修改它:classpath:/view/


            controller頁(yè)面跳轉(zhuǎn)

            使用ModelAndView進(jìn)行跳轉(zhuǎn),將數(shù)據(jù)add進(jìn)去

              @RequestMapping("/login.do")
              public ModelAndView login(User user){
                  Result result=userService.login(user);
                  ModelAndView mv=new ModelAndView();
                  mv.addObject("newText","你好,Thymeleaf!");
                  mv.addObject("gender","1");
                  mv.addObject("userList",result.getData());
                  if(result.getData()!=null) {
                      mv.addObject("loginUser",result.getData());
                  }
                  mv.setViewName("index.html");
                  return mv;
              }


            html頁(yè)面取值

            引入命名空間,避免校驗(yàn)錯(cuò)誤<html xmlns:th="http://www.thymeleaf.org">

          <!DOCTYPE html>
          <!--解決idea thymeleaf 表達(dá)式模板報(bào)紅波浪線(xiàn)-->
          <!--suppress ALL -->
          <html xmlns:th="http://www.thymeleaf.org">
          <head>
              <meta charset="UTF-8" />
              <title>srpingboot</title>
          </head>
          <body>
              <!-- 屬性替換,其他屬性同理 -->
              <h1 th:text="${newText}">Hello World</h1>
              <!--
                  設(shè)置多個(gè)attr
                  th:attr="id=${user.id},data-xxx=${user.xxx},data-yyy=${user.yyy}"
          
                  片段的使用、傳值和調(diào)用
                  <div th:fragment="common(text1,text2)">
                      ...
                  </div>
                  th:insert 是最簡(jiǎn)單的:它只是插入指定的片段作為其主機(jī)標(biāo)簽的主體。
                  <div th:insert="base ::common(${text1},${text2})"></div>
          
                  th:replace實(shí)際上用指定的片段替換它的主機(jī)標(biāo)簽。
                  <div th:replace="base ::common(${text1},${text2})"></div>
              
               三目表達(dá)式:
               <h3 th:text="${loginUser !=null} ? ${loginUser.username} : '請(qǐng)登錄'"></h3> 
          
              -->
          
              <!-- if-else -->
              <h3 th:if="${loginUser} ne null" th:text="${loginUser.username}"></h3>
              <h3 th:unless="${loginUser} ne null">請(qǐng)登錄</h3>
          
              <!-- switch -->
              <div th:switch="${gender}">
                  <p th:case="'1'">男</p>
                  <p th:case="'0'">女</p>
                  <!-- th:case="*"  類(lèi)似switch中的default -->
                  <p th:case="*">其他</p>
              </div>
          
              <!-- 
              each
              其中,iterStat參數(shù)為狀態(tài)變量,常用的屬性有
              index 迭代下標(biāo),從0開(kāi)始
              count 迭代下標(biāo),從1開(kāi)始
              size 迭代元素的總量
              current 當(dāng)前元素
             -->
              <table>
                  <thead>
                      <tr>
                          <th>id</th>
                          <th>username</th>
                          <th>password</th>
                          <th>created</th>
                          <th>description</th>
                      </tr>
                  </thead>
                  <tbody>
                      <tr th:each="user,iterStat : ${userList}">
                          <td th:text="${user.id}"></td>
                          <td th:text="${user.username}"></td>
                          <td th:text="${user.password}"></td>
                          <td th:text="${user.created}"></td>
                          <td th:text="${user.description}"></td>
                      </tr>
                  </tbody>
              </table>
          </body>
          <!-- 引入靜態(tài)資源 -->
          <script th:src="@{/js/jquery-1.9.1.min.js}" type="application/javascript"></script>
          </html>


            本地打開(kāi)


            服務(wù)容器打開(kāi),登錄失敗頁(yè)面效果


            服務(wù)容器打開(kāi),登錄成功頁(yè)面效果


            標(biāo)準(zhǔn)表達(dá)式

            簡(jiǎn)單表達(dá)
            變量表達(dá)式: ${...}
            選擇變量表達(dá)式: *{...}
            消息表達(dá)式: #{...}
            鏈接網(wǎng)址表達(dá)式: @{...}
            片段表達(dá)式: ~{...}

            字面
            文本文字:'one text','Another one!',...
            號(hào)碼文字:0,34,3.0,12.3,...
            布爾文字:true,false
            空字面: null
            文字標(biāo)記:one,sometext,main,...
            文字操作:
            字符串連接: +
            文字替換: |The name is ${name}|

            算術(shù)運(yùn)算
            二元運(yùn)算符:+,-,*,/,%
            減號(hào)(一元運(yùn)算符): -

            布爾運(yùn)算
            二元運(yùn)算符:and,or
            布爾否定(一元運(yùn)算符): !,not

            比較和平等
            比較:>,<,>=,<=(gt,lt,ge,le)
            等值運(yùn)算符:==,!=(eq,ne)

            條件運(yùn)算符
            if-then: (if) ? (then)
            if-then-else: (if) ? (then) : (else)
            default: (value) ?: (defaultvalue)

            特殊特征符
            無(wú)操作: _

            所有這些功能都可以組合和嵌套,例:
            'User is of type ' + (user.isAdmin()?′Administrator′:(user.isAdmin()?′Administrator′:({user.type} ?: 'Unknown'))

            官網(wǎng)表達(dá)式介紹:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax


            后記

            springboot+thymeleaf,前后端分離已經(jīng)成為了趨勢(shì),這里進(jìn)行學(xué)習(xí)記錄整理,以免以后又要到處查資料。


            補(bǔ)充

            2019-07-24補(bǔ)充:除此之外,thymeleaf還內(nèi)置了很多對(duì)象,可以從上下文獲取數(shù)據(jù),還有好多對(duì)象的操作方法,具體請(qǐng)看:

            附錄A:表達(dá)式基本對(duì)象:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects

            附錄B:表達(dá)式實(shí)用程序?qū)ο螅篽ttps://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects

            比如:

            在頁(yè)面獲取項(xiàng)目路徑

              //項(xiàng)目路徑
              var ctx=[[${#request.getContextPath()}]];

            判斷集合長(zhǎng)度

          <p th:if="${#lists.size(list)} < 25">
              <p>list集合長(zhǎng)度小于25!</p>
          </p>

            字符串全大寫(xiě)、小寫(xiě)

          <p th:text="${#strings.toUpperCase(name)}"></p>
          
          <p th:text="${#strings.toLowerCase(name)}"></p>

            有一點(diǎn)要注意,使用這些內(nèi)置對(duì)象,方法傳參里面不需要再用${}來(lái)取值了,例如,后臺(tái)傳過(guò)來(lái)的名稱(chēng)叫name

            錯(cuò)誤使用:

          <p th:text="${#strings.toUpperCase($(name))}"></p>

            正確使用:

          <p th:text="${#strings.toUpperCase(name)}"></p>


            更多內(nèi)置對(duì)象方法請(qǐng)看官網(wǎng)!


            補(bǔ)充:本地環(huán)境不報(bào)錯(cuò),Linux環(huán)境下報(bào)錯(cuò),模板不存在:Error resolving template [/bam/login], template might not exist or might not be accessible by any of the configured Template Resolvers

            解決:

            把/去掉就可以了




            代碼開(kāi)源

            代碼已經(jīng)開(kāi)源、托管到我的GitHub、碼云:

            GitHub:https://github.com/huanzi-qch/springBoot

            碼云:https://gitee.com/huanzi-qch/springBoot



          版權(quán)聲明

          作者:huanzi-qch

          出處:https://www.cnblogs.com/huanzi-qch

          若標(biāo)題中有“轉(zhuǎn)載”字樣,則本文版權(quán)歸原作者所有。若無(wú)轉(zhuǎn)載字樣,本文版權(quán)歸作者所有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁(yè)面明顯位置給出原文鏈接,否則保留追究法律責(zé)任的權(quán)利.

          文:https://www.xncoding.com/2017/07/01/spring/sb-thymeleaf.html

          Thymeleaf 是一個(gè)跟 Velocity、FreeMarker 類(lèi)似的模板引擎,它可以完全替代 JSP 。相較與其他的模板引擎,它有如下三個(gè)極吸引人的特點(diǎn):

          1. Thymeleaf 在有網(wǎng)絡(luò)和無(wú)網(wǎng)絡(luò)的環(huán)境下皆可運(yùn)行,即它可以讓美工在瀏覽器查看頁(yè)面的靜態(tài)效果,也可以讓程序員在服務(wù)器查看帶數(shù)據(jù)的動(dòng)態(tài)頁(yè)面效果。
          2. Thymeleaf 開(kāi)箱即用的特性。它提供標(biāo)準(zhǔn)和spring標(biāo)準(zhǔn)兩種方言,可以直接套用模板實(shí)現(xiàn)JSTL、 OGNL表達(dá)式效果,避免每天套模板、該jstl、改標(biāo)簽的困擾。
          3. Thymeleaf 提供spring標(biāo)準(zhǔn)方言和一個(gè)與 SpringMVC 完美集成的可選模塊,可以快速的實(shí)現(xiàn)表單綁定、屬性編輯器、國(guó)際化等功能。

          目前最新版本是Thymeleaf 3,官網(wǎng)地址:http://www.thymeleaf.org

          本篇將介紹如何在SpringBoot中集成Thymeleaf構(gòu)建Web應(yīng)用。

          maven依賴(lài)

          <properties>

          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

          <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

          <java.version>1.8</java.version>

          <thymeleaf.version>3.0.7.RELEASE</thymeleaf.version>

          <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>

          </properties>

          <dependencies>

          <dependency>

          <groupId>org.springframework.boot</groupId>

          <artifactId>spring-boot-starter-web</artifactId>

          <exclusions>

          <exclusion>

          <groupId>org.springframework.boot</groupId>

          <artifactId>spring-boot-starter-tomcat</artifactId>

          </exclusion>

          </exclusions>

          </dependency>

          <dependency>

          <groupId>org.springframework.boot</groupId>

          <artifactId>spring-boot-starter-jetty</artifactId>

          </dependency>

          <dependency>

          <groupId>org.springframework.boot</groupId>

          <artifactId>spring-boot-starter-thymeleaf</artifactId>

          </dependency>

          </dependencies>

          資源目錄

          Spring Boot默認(rèn)提供靜態(tài)資源目錄位置需置于classpath下,目錄名需符合如下規(guī)則:

          1. /static
          2. /public
          3. /resources
          4. /META-INF/resources

          舉例:我們可以在src/main/resources/目錄下創(chuàng)建static,在該位置放置一個(gè)圖片文件pic.jpg。 啟動(dòng)程序后,嘗試訪問(wèn)http://localhost:8080/pic.jpg。如能顯示圖片,配置成功。

          SpringBoot的默認(rèn)模板路徑為:src/main/resources/templates

          添加頁(yè)面

          這里我在src/main/resources/templates下面添加一個(gè)index.html首頁(yè),同時(shí)引用到一些css、js文件,看看Thymeleaf 3的語(yǔ)法:

          <!DOCTYPE html>

          <html xmlns="http://www.w3.org/1999/xhtml"

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

          <head>

          <meta charset="utf-8">

          <meta name="viewport" content="width=device-width, initial-scale=1.0">

          <meta name="renderer" content="webkit">

          <title>首頁(yè)</title>

          <link rel="shortcut icon" th:href="@{/favicon.ico}"/>

          <link th:href="@{/static/css/bootstrap.min.css}" rel="stylesheet"/>

          <link th:href="@{/static/css/font-awesome.min.css}" rel="stylesheet"/>

          </head>

          <body class="fixed-sidebar full-height-layout gray-bg" style="overflow:hidden">

          <div id="wrapper">

          <h1 th:text="${msg}"></h1>

          </div>

          <script th:src="@{/static/js/jquery.min.js}"></script>

          <script th:src="@{/static/js/bootstrap.min.js}"></script>

          </body>

          </html>

          頁(yè)面中幾個(gè)地方說(shuō)明一下:

          <html xmlns="http://www.w3.org/1999/xhtml"

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

          加上這個(gè)命名空間后就能在頁(yè)面中使用Thymeleaf自己的標(biāo)簽了,以th:開(kāi)頭。

          連接語(yǔ)法 th:href="@{/static/css/bootstrap.min.css}"

          訪問(wèn)Model中的數(shù)據(jù)語(yǔ)法 th:text="${msg}"

          這里我在頁(yè)面里顯示的是一個(gè)鍵為msg的消息,需要后臺(tái)傳遞過(guò)來(lái)。

          Thymeleaf 3的詳細(xì)語(yǔ)法規(guī)則請(qǐng)參考 官網(wǎng)教程

          編寫(xiě)Controller

          接下來(lái)編寫(xiě)控制器類(lèi),將URL / 和 /index 都返回index.html頁(yè)面:

          @Controller

          public class IndexController {

          private static final Logger _logger=LoggerFactory.getLogger(IndexController.class);

          /**

          * 主頁(yè)

          *

          * @param model

          * @return

          */

          @RequestMapping({"/", "/index"})

          public String index(Model model) {

          model.addAttribute("msg", "welcome you!");

          return "index";

          }

          }

          這里,我再model里面添加了一個(gè)屬性,key=msg,值為welcome you!。

          接下來(lái)啟動(dòng)應(yīng)用后,打開(kāi)首頁(yè)看看效果如何。消息正確顯示,成功!。

          . Thymeleaf 簡(jiǎn)介

          Thymeleaf 是新一代 Java 模板引擎,與 Velocity、FreeMarker 等傳統(tǒng) Java 模板引擎不同,Thymeleaf 支持 HTML 原型,其文件后綴為“.html”,因此它可以直接被瀏覽器打開(kāi),此時(shí)瀏覽器會(huì)忽略未定義的 Thymeleaf 標(biāo)簽屬性,展示 thymeleaf 模板的靜態(tài)頁(yè)面效果;當(dāng)通過(guò) Web 應(yīng)用程序訪問(wèn)時(shí),Thymeleaf 會(huì)動(dòng)態(tài)地替換掉靜態(tài)內(nèi)容,使頁(yè)面動(dòng)態(tài)顯示

          html<!DOCTYPE html>
          <html lang="en" xmlns:th="http://www.thymeleaf.org">
          <head>
              <meta charset="UTF-8">
              <title>Title</title>
          </head>
          <body>
          <!--th:text 為 Thymeleaf 屬性,用于在展示文本-->
          <h1 th:text="歡迎您來(lái)到Thymeleaf">歡迎您訪問(wèn)靜態(tài)頁(yè)面 HTML</h1>
          </body>
          </html>
          

          當(dāng)直接使用瀏覽器打開(kāi)時(shí),瀏覽器展示結(jié)果如下。

          歡迎您訪問(wèn)靜態(tài)頁(yè)面HTML

          當(dāng)通過(guò) Web 應(yīng)用程序訪問(wèn)時(shí),瀏覽器展示結(jié)果如下。

          歡迎您來(lái)到Thymeleaf

          Thymeleaf 的特點(diǎn):

          • 動(dòng)靜結(jié)合:Thymeleaf 既可以直接使用瀏覽器打開(kāi),查看頁(yè)面的靜態(tài)效果,也可以通過(guò) Web 應(yīng)用程序進(jìn)行訪問(wèn),查看動(dòng)態(tài)頁(yè)面效果。
          • 開(kāi)箱即用:Thymeleaf 提供了 Spring 標(biāo)準(zhǔn)方言以及一個(gè)與 SpringMVC 完美集成的可選模塊,可以快速的實(shí)現(xiàn)表單綁定、屬性編輯器、國(guó)際化等功能。
          • 多方言支持:它提供了 Thymeleaf 標(biāo)準(zhǔn)和 Spring 標(biāo)準(zhǔn)兩種方言,可以直接套用模板實(shí)現(xiàn) JSTL、 OGNL 表達(dá)式;必要時(shí),開(kāi)發(fā)人員也可以擴(kuò)展和創(chuàng)建自定義的方言。
          • 與 SpringBoot 完美整合:SpringBoot 為 Thymeleaf 提供了的默認(rèn)配置,并且還為 Thymeleaf 設(shè)置了視圖解析器,因此 Thymeleaf 可以與 Spring Boot 完美整合。

          2. Thymeleaf 語(yǔ)法規(guī)則

          在使用 Thymeleaf 之前,首先要在頁(yè)面的 html 標(biāo)簽中聲明名稱(chēng)空間,示例代碼如下。

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

          在 html 標(biāo)簽中聲明此名稱(chēng)空間,可避免編輯器出現(xiàn) html 驗(yàn)證錯(cuò)誤,但這一步并非必須進(jìn)行的,即使我們不聲明該命名空間,也不影響 Thymeleaf 的使用。

          2.1 標(biāo)準(zhǔn)表達(dá)式語(yǔ)法

          2.1.1 變量表達(dá)式

          使用${}包裹的表達(dá)式被稱(chēng)為變量表達(dá)式,該表達(dá)式具有以下功能:

          • 獲取對(duì)象的屬性和方法 使用變量表達(dá)式可以獲取對(duì)象的屬性和方法,例如,獲取 person 對(duì)象的 lastName 屬性,表達(dá)式形式如下:
          • html
          • ${person.lastName}
          • 使用內(nèi)置的基本對(duì)象 使用變量表達(dá)式還可以使用內(nèi)置基本對(duì)象,獲取內(nèi)置對(duì)象的屬性,調(diào)用內(nèi)置對(duì)象的方法。 Thymeleaf 中常用的內(nèi)置基本對(duì)象如下: 例如,我們通過(guò)以下 2 種形式,都可以獲取到 session 對(duì)象中的 map 屬性:
          • html
          • ${#session.getAttribute('map')} ${session.map}
          • 使用內(nèi)置的工具對(duì)象
          • 例如,我們可以使用內(nèi)置工具對(duì)象 strings 的 equals 方法,來(lái)判斷字符串與對(duì)象的某個(gè)屬性是否相等,代碼如下。
          • html
          • ${#strings.equals('編程幫',name)}

          2.1.2 選擇變量表達(dá)式

          選擇變量表達(dá)式與變量表達(dá)式功能基本一致,只是在變量表達(dá)式的基礎(chǔ)上增加了與 th:object 的配合使用。當(dāng)使用 th:object 存儲(chǔ)一個(gè)對(duì)象后,我們可以在其后代中使用選擇變量表達(dá)式(*{...})獲取該對(duì)象中的屬性,其中,“*”即代表該對(duì)象。

          html<div th:object="${session.user}" >
              <p th:text="*{fisrtName}">firstname</p>
          </div>
          

          th:object 用于存儲(chǔ)一個(gè)臨時(shí)變量,該變量只在該標(biāo)簽及其后代中有效,在后面的內(nèi)容“th 屬性”中我詳細(xì)介紹。

          2.1.3 鏈接表達(dá)式

          不管是靜態(tài)資源的引用,還是 form 表單的請(qǐng)求,凡是鏈接都可以用鏈接表達(dá)式 (@{...})。

          鏈接表達(dá)式的形式結(jié)構(gòu)如下:

          • 無(wú)參請(qǐng)求:@{/xxx}
          • 有參請(qǐng)求:@{/xxx(k1=v1,k2=v2)}

          例如使用鏈接表達(dá)式引入 css 樣式表,代碼如下。

          html<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
          

          2.1.4 國(guó)際化表達(dá)式

          消息表達(dá)式一般用于國(guó)際化的場(chǎng)景。結(jié)構(gòu)如下。

          htmlth:text="#{msg}"
          

          注意:此處了解即可,我們會(huì)在后面的章節(jié)中詳細(xì)介紹。

          2.1.5 片段引用表達(dá)式

          片段引用表達(dá)式用于在模板頁(yè)面中引用其他的模板片段,該表達(dá)式支持以下 2 中語(yǔ)法結(jié)構(gòu):

          • 推薦:~{templatename::fragmentname}
          • 支持:~{templatename::#id}

          以上語(yǔ)法結(jié)構(gòu)說(shuō)明如下:

          • templatename:模版名,Thymeleaf 會(huì)根據(jù)模版名解析完整路徑:/resources/templates/templatename.html,要注意文件的路徑。
          • fragmentname:片段名,Thymeleaf 通過(guò) th:fragment 聲明定義代碼塊,即:th:fragment="fragmentname"
          • id:HTML 的 id 選擇器,使用時(shí)要在前面加上 # 號(hào),不支持 class 選擇器。

          2.2 th 屬性

          Thymeleaf 還提供了大量的 th 屬性,這些屬性可以直接在 HTML 標(biāo)簽中使用,其中常用 th 屬性及其示例如下表。

          屬性

          描述

          示例

          th:id

          替換 HTML 的 id 屬性

          <input id="html-id" th:id="thymeleaf-id" />

          th:text

          文本替換,轉(zhuǎn)義特殊字符

          <h1 th:text="hello,bianchengbang" >hello</h1>

          th:untext

          文本替換,文本替換,不轉(zhuǎn)義特殊字符

          <div th:utext="'<h1>歡迎來(lái)到編程幫!</h1>'" >歡迎你</div>

          th:object

          在父標(biāo)簽選擇對(duì)象,子標(biāo)簽使用 *{…} 選擇表達(dá)式選取值。沒(méi)有選擇對(duì)象,那子標(biāo)簽使用選擇表達(dá)式和 ${…} 變量表達(dá)式是一樣的效果。同時(shí)即使選擇了對(duì)象,子標(biāo)簽仍然可以使用變量表達(dá)式。

          <div th:object="${session.user}" > <p th:text="*{fisrtName}">firstname</p> </div>

          th:value

          替換 value 屬性

          <input th:value="${user.name}" />

          th:with

          局部變量賦值運(yùn)算

          <div th:with="isEvens=${prodStat.count}%2==0" th:text="${isEvens}"></div>

          th:style

          設(shè)置樣式

          <div th:style="'color:#F00; font-weight:bold'">編程幫 www.biancheng.net</div>

          th:onclick

          點(diǎn)擊事件

          <td th:onclick="'getInfo()'"></td>

          th:each

          遍歷,支持 Iterable、Map、數(shù)組等。

          <table> <tr th:each="m:${session.map}"> <td th:text="${m.getKey()}"></td> <td th:text="${m.getValue()}"></td> </tr></table>

          th:if

          根據(jù)條件判斷是否需要展示此標(biāo)簽

          <a th:if="${userId==collect.userId}">

          th:unless

          和 th:if 判斷相反,滿(mǎn)足條件時(shí)不顯示

          <div th:unless="${m.getKey()=='name'}" ></div>

          th:switch

          與 Java 的 switch case語(yǔ)句類(lèi)似通常與 th:case 配合使用,根據(jù)不同的條件展示不同的內(nèi)容

          <div th:switch="${name}"> <span th:case="a">編程幫</span> <span th:case="b">www.biancheng.net</span></div>

          th:fragment

          模板布局,類(lèi)似 JSP 的 tag,用來(lái)定義一段被引用或包含的模板片段

          <footer th:fragment="footer">插入的內(nèi)容</footer>

          th:insert

          布局標(biāo)簽;將使用 th:fragment 屬性指定的模板片段(包含標(biāo)簽)插入到當(dāng)前標(biāo)簽中

          <div th:insert="commons/bar::footer"></div>

          th:replace

          布局標(biāo)簽;使用 th:fragment 屬性指定的模板片段(包含標(biāo)簽)替換當(dāng)前整個(gè)標(biāo)簽

          <div th:replace="commons/bar::footer"></div>

          th:selected

          select 選擇框選中

          <select> <option>---</option> <option th:selected="${name=='a'}"> 編程幫 </option> <option th:selected="${name=='b'}"> www.biancheng.net </option></select>

          th:src

          替換 HTML 中的 src 屬性

          <img th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" />

          th:inline

          內(nèi)聯(lián)屬性;該屬性有 text、none、javascript 三種取值,在 <script> 標(biāo)簽中使用時(shí),js 代碼中可以獲取到后臺(tái)傳遞頁(yè)面的對(duì)象。

          <script type="text/javascript" th:inline="javascript"> var name=/*[[${name}]]*/ ianchengbang'; alert(name)</script>

          th:action

          替換表單提交地址

          <form th:action="@{/user/login}" th:method="post"></form>

          3. Thymeleaf 公共頁(yè)面抽取

          在 Web 項(xiàng)目中,通常會(huì)存在一些公共頁(yè)面片段(重復(fù)代碼),例如頭部導(dǎo)航欄、側(cè)邊菜單欄和公共的 js css 等。我們一般會(huì)把這些公共頁(yè)面片段抽取出來(lái),存放在一個(gè)獨(dú)立的頁(yè)面中,然后再由其他頁(yè)面根據(jù)需要進(jìn)行引用,這樣可以消除代碼重復(fù),使頁(yè)面更加簡(jiǎn)潔。

          3.1 抽取公共頁(yè)面

          Thymeleaf 作為一種優(yōu)雅且高度可維護(hù)的模板引擎,同樣支持公共頁(yè)面的抽取和引用。我們可以將公共頁(yè)面片段抽取出來(lái),存放到一個(gè)獨(dú)立的頁(yè)面中,并使用 Thymeleaf 提供的 th:fragment 屬性為這些抽取出來(lái)的公共頁(yè)面片段命名。 示例 1 將公共頁(yè)面片段抽取出來(lái),存放在 commons.html 中,代碼如下。

          html<div th:fragment="fragment-name" id="fragment-id">
              <span>公共頁(yè)面片段</span>
          </div>
          

          3.2 引用公共頁(yè)面

          在 Thymeleaf 中,我們可以使用以下 3 個(gè)屬性,將公共頁(yè)面片段引入到當(dāng)前頁(yè)面中。

          • th:insert:將代碼塊片段整個(gè)插入到使用了 th:insert 屬性的 HTML 標(biāo)簽中;
          • th:replace:將代碼塊片段整個(gè)替換使用了 th:replace 屬性的 HTML 標(biāo)簽中;
          • th:include:將代碼塊片段包含的內(nèi)容插入到使用了 th:include 屬性的 HTML 標(biāo)簽中。

          使用上 3 個(gè)屬性引入頁(yè)面片段,都可以通過(guò)以下 2 種方式實(shí)現(xiàn)。

          • ~{templatename::selector}:模板名::選擇器
          • ~{templatename::fragmentname}:模板名::片段名

          通常情況下,{} 可以省略,其行內(nèi)寫(xiě)法為 [[{...}]] 或 [({...})],其中 [[{...}]] 會(huì)轉(zhuǎn)義特殊字符,[(~{...})] 則不會(huì)轉(zhuǎn)義特殊字符。

          示例 2

          1. 在頁(yè)面 fragment.html 中引入 commons.html 中聲明的頁(yè)面片段,可以通過(guò)以下方式實(shí)現(xiàn)。
          html<!--th:insert 片段名引入-->
          <div th:insert="commons::fragment-name"></div>
          <!--th:insert id 選擇器引入-->
          <div th:insert="commons::#fragment-id"></div>
          ------------------------------------------------
          <!--th:replace 片段名引入-->
          <div th:replace="commons::fragment-name"></div>
          <!--th:replace id 選擇器引入-->
          <div th:replace="commons::#fragment-id"></div>
          ------------------------------------------------
          <!--th:include 片段名引入-->
          <div th:include="commons::fragment-name"></div>
          <!--th:include id 選擇器引入-->
          <div th:include="commons::#fragment-id"></div>
          
          1. 啟動(dòng) Spring Boot,使用瀏覽器訪問(wèn) fragment.html,查看源碼,結(jié)果如下。
          html<!--th:insert 片段名引入-->
          <div>
              <div id="fragment-id">
                  <span>公共頁(yè)面片段</span>
              </div>
          </div>
          <!--th:insert id 選擇器引入-->
          <div>
              <div id="fragment-id">
                  <span>公共頁(yè)面片段</span>
              </div>
          </div>
          ------------------------------------------------
          <!--th:replace 片段名引入-->
          <div id="fragment-id">
              <span>公共頁(yè)面片段</span>
          </div>
          <!--th:replace id 選擇器引入-->
          <div id="fragment-id">
              <span>公共頁(yè)面片段</span>
          </div>
          ------------------------------------------------
          <!--th:include 片段名引入-->
          <div>
              <span>公共頁(yè)面片段</span>
          </div>
          <!--th:include id 選擇器引入-->
          <div>
              <span>公共頁(yè)面片段</span>
          </div>
          

          3.3 傳遞參數(shù)

          Thymeleaf 在抽取和引入公共頁(yè)面片段時(shí),還可以進(jìn)行參數(shù)傳遞,大致步驟如下: 1.傳入?yún)?shù); 2.使用參數(shù)。

          3.3.1 傳入?yún)?shù)

          引用公共頁(yè)面片段時(shí),我們可以通過(guò)以下 2 種方式,將參數(shù)傳入到被引用的頁(yè)面片段中: 模板名::選擇器名或片段名(參數(shù)1=參數(shù)值1,參數(shù)2=參數(shù)值2) 模板名::選擇器名或片段名(參數(shù)值1,參數(shù)值2)

          注:若傳入?yún)?shù)較少時(shí),一般采用第二種方式,直接將參數(shù)值傳入頁(yè)面片段中; 若參數(shù)較多時(shí),建議使用第一種方式,明確指定參數(shù)名和參數(shù)值,。

          示例代碼如下:

          java<!--th:insert 片段名引入-->
          <div th:insert="commons::fragment-name(var1='insert-name',var2='insert-name2')"></div>
          <!--th:insert id 選擇器引入-->
          <div th:insert="commons::#fragment-id(var1='insert-id',var2='insert-id2')"></div>
          ------------------------------------------------
          <!--th:replace 片段名引入-->
          <div th:replace="commons::fragment-name(var1='replace-name',var2='replace-name2')"></div>
          <!--th:replace id 選擇器引入-->
          <div th:replace="commons::#fragment-id(var1='replace-id',var2='replace-id2')"></div>
          ------------------------------------------------
          <!--th:include 片段名引入-->
          <div th:include="commons::fragment-name(var1='include-name',var2='include-name2')"></div>
          <!--th:include id 選擇器引入-->
          <div th:include="commons::#fragment-id(var1='include-id',var2='include-id2')"></div>
          

          3.3.2 使用參數(shù)

          在聲明頁(yè)面片段時(shí),我們可以在片段中聲明并使用這些參數(shù),例如:

          java<!--使用 var1 和 var2 聲明傳入的參數(shù),并在該片段中直接使用這些參數(shù) -->
          <div th:fragment="fragment-name(var1,var2)" id="fragment-id">
              <p th:text="'參數(shù)1:'+${var1} + '-------------------參數(shù)2:' + ${var2}">...</p>
          </div>
          

          啟動(dòng) Spring Boot,使用瀏覽器訪問(wèn) fragment.html,結(jié)果如下圖。


          主站蜘蛛池模板: 精品香蕉一区二区三区| 亚洲午夜福利AV一区二区无码| 国模丽丽啪啪一区二区| 国产福利一区二区在线视频 | 精品无码人妻一区二区免费蜜桃| 国产高清一区二区三区视频| 国产午夜精品一区二区三区嫩草| 色国产在线视频一区| 久久青草国产精品一区| 色综合一区二区三区| 亚洲一区二区三区丝袜| 无码少妇一区二区性色AV| 日韩精品一区二区三区影院 | 日韩经典精品无码一区| 亚洲AV无码一区二区二三区软件| 亚洲av高清在线观看一区二区| 日韩人妻一区二区三区免费| 伊人激情AV一区二区三区| 无码日韩AV一区二区三区| 3d动漫精品啪啪一区二区中| 国产精品区一区二区三在线播放 | 亚洲第一区二区快射影院| 嫩B人妻精品一区二区三区| 视频一区二区精品的福利| 老鸭窝毛片一区二区三区| 99久久精品日本一区二区免费 | 久久精品日韩一区国产二区| 久久国产精品无码一区二区三区 | 99久久无码一区人妻a黑| 无码人妻精品一区二区三区东京热| 日韩av片无码一区二区三区不卡| AV鲁丝一区鲁丝二区鲁丝三区| 88国产精品视频一区二区三区| 夜夜添无码一区二区三区| 日韩精品免费一区二区三区| 高清国产AV一区二区三区| 狠狠色婷婷久久一区二区三区| 日本韩国黄色一区二区三区| 国产A∨国片精品一区二区| 中文字幕aⅴ人妻一区二区| 日韩AV无码久久一区二区|