spring-boot周邊遊(三)Thymeleaf-1 一個簡單的demo以及初識Standard Dialect

Thymeleaf簡介

配置Thymeleaf

這個教程是基於maven環境進行配置的。css

1.在resources文件夾之下新加兩個文件夾,分別爲templates和static,其中templates用於存放界面HTML文件,而static則用於存儲靜態文件好比js,css或img。目錄格式以下:html

-project
  -src
    -main
      -java
      -resources
        -templates
        -static
        -config
          -application.yml
          -application-test.yml
          -application-validate.yml
    -test
  -pom.xml

2.pom.xml文件中添加依賴:java

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

3.在.properties文件或是.yml文件中添加thymeleaf配置
.properties文件中配置內容以下:web

########################################################
###THYMELEAF (ThymeleafAutoConfiguration)
########################################################
#配置項目的HTML路徑
spring.thymeleaf.prefix=classpath:/templates/
#後綴
spring.thymeleaf.suffix=.html
#會開啓嚴格的HTML格式檢查,所以若是想要關閉它,就將其值設置爲LEGACYHTML5
#spring.thymeleaf.mode=HTML5 #LEGACYHTML5 若是想要關閉強制的語法檢查
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
# 關閉了換從,從而支持熱部署
spring.thymeleaf.cache=false

.yml文件中配置內容以下:面試

spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    encoding: UTF-8
    content-type: text/html
    cache: false
    mode: LEGACYHTML5

至此環境配置完成。Spring支持多種方式配置Thymeleaf包括代碼,XML等等。這裏咱們採用yml文件的方式。spring

4.編寫demo
在resources/templates目錄下新建一個hello.html文件,內容以下:express

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Welcome Page</title>
</head>
<body>
<!--從上下文中獲取name屬性並填寫到p標籤中-->
    <p th:text="'hello, '+${name}">hello! my new friend!</p>
</body>
</html>

這裏須要注意的是,要在html標籤中加入xmlns:th="http://www.thymeleaf.org"數組

編寫一個controller,內容以下:瀏覽器

@Controller
@RequestMapping("/")
public class TestController {

    @GetMapping("/hello")
    public String welcome(Model model){
        model.addAttribute("name", "小夥伴");
        return "hello";
    }
}

這一部分的內容涉及Spring-mvc,這裏暫時不細講,各位只需copy代碼便可。spring-mvc

完成後運行Application.java啓動spring-boot項目,Application.java內容以下:

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.Arrays;
@EnableJpaAuditing
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter{

    public static void main(String[] args){
        SpringApplication.run(Application.class);
    }

    /**
     * 在啓動時輸出找到的全部的bean
     * @param ctx
     * @return
     */
    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {

            System.out.println("Let's inspect the beans provided by Spring Boot:");

            String[] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            for (String beanName : beanNames) {
                System.out.println(beanName);
            }

        };
    }

}

啓動完畢後在瀏覽器中輸入http://localhost:PORT/hello。這裏的PORT是指端口號,能夠在配置文件中使用server.port:8080配置。使用yaml配置的話請自行轉化。

這是的界面顯示以下:

clipboard.png

Thymeleaf basic

1.Thymeleaf支持多種模式(mode)

  • HTML(包括HTML5, HTML 4 and XHTML.)不會進行很是嚴格的語法檢查
  • XML (嚴格的語法檢查,若是不符合標準會拋出異常)
  • TEXT
  • JAVASCRIPT (意味着能夠像在HTML中的語法同樣在JS中使用)
  • CSS (同上)
  • RAW

2.Standard Dialect

An object that applies some logic to a markup artifact (a tag, some text, a comment, or a mere placeholder if templates are not markup) is called a processor, and a set of these processors – plus perhaps some extra artifacts – is what a dialect is normally comprised of.

dialect由processors和artifacts構成。processor是指將一些邏輯施加於markup元素之上。dialect將在後面繼續介紹,它是thymeleaf的一個重要成分。這裏想介紹一下,就是Thymeleaf對SpEL有很是良好的支持,並且以前使用ONGL語法的同志也能夠很是快速的過渡。同時這種語法優於jsp的優勢在於它支持原生的HTML語法,從而在預覽的時候不會由於JSP語法而必須先經過服務器渲染。

Standard Dialect

th:text: 更換當前標籤之下的text內容,例如 <p th:text="hello"></p>轉化後成爲 <p>hello</p>
th:utext: 非轉義語法,也就是當存在如HTML語義中的標籤 <span>不會將其轉義爲 &lt;span&rt;

Standard Syntax Expression

在官網上列舉了全部的標準的語法,有興趣的能夠戳文末的連接去了解。這裏簡單介紹一下其中的幾種並舉例說明。
爲了便於理解,這裏先介紹一下,th:text屬性會將所在的標籤的內容改變爲th:text的值。並且th:text支持動態賦值。

Message Expression #{...}

假設咱們如今想要把一些公共用語放在一個配置文件中,而且這個配置文件能夠支持多國語言。那麼咱們就能夠經過#{}獲取配置文件中的內容。Thymeleaf默認每一個HTML的配置文件位於同目錄之下的同名的.properties文件中。如今咱們來嘗試一下,在以前的hello.html之中添加一段代碼,內容以下:

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Welcome Page</title>
</head>
<body>
    <!--從上下文中獲取name屬性並填寫到p標籤中-->
    <p th:text="'hello, '+${name}">hello! my new friend!</p>
    
    <!--添加這一段代碼-->
    <p th:utext="#{welcome.login}"></p>
</body>
</html>

而後在同目錄下添加一個hello.properties文件,內容以下:

welcome.login:welcome to this <b>damn</b> website

這時開啓項目就能夠看見第二個<p>的text爲配置文件中的內容。

假設這時有一個新需求,好比咱們但願在歡迎詞中包含用戶名體現個性化,那麼咱們可使用以下的方式:
hello.properties使用{}佔位符

welcome.login:welcome to this <b>damn</b> website,{0}

hello.html ${session.user.name}從session中獲取用戶名做爲參數傳遞給message,股關於${}會在下一小節詳細介紹。若是有多個參數須要傳遞,能夠用逗號隔開

<p th:utext="#{welcome.login(${session.user.name})}"></p>

Variable Expressions ${...}

${}屬於OGNL語法,而在spring-mvc中會被替代爲SpEL,可是兩者的語法在大多數場景下基本相同。
下面是一些簡單範例:

${person.father.name}: 至關於person.getFather().getName()
${personsByName['Stephen Zucchini'].age}: 獲取map對象personByName中名稱爲Stephen Zucchini的人的年齡
${personsArray[0].name}: 獲取personsArray數組對象中第一個對象的name
${person.createCompleteName()} : 容許直接調用對象中的方法

Thymeleaf還考慮到你可能須要在界面中調用到不少的上下文屬性,或者是使用一些工具,所以內置了一下對象和方法供你們使用。這裏直接摘抄了官網,有興趣的能夠直接去官網進行了解。

clipboard.png

clipboard.png

Selection Variable *{...}

被標記爲*{x}將不會再上下文中尋找x屬性,而是會去最近選中的對象中尋找x屬性。若是沒有最近選中的對象,那麼*{...}#{...}所執行的操做相同。
那麼咱們如何才能知道是否選中對象呢,這是須要使用th:object屬性來標記被選中的對象。下面舉個栗子:
好比如今咱們有一本書,而且咱們但願在界面中展現這本書的詳細信息,包括書的ISBN,名稱(name)和價格(price),那麼咱們的界面能夠是醬的

<div th:object="${book}">
    <p th:text="*{ISBN}"></p>
    <p th:text="*{name}"></p>
    <p th:text="*{price}"></p>
</div>

這段代碼等價於

<div>
    <p th:text="${book.ISBN}"></p>
    <p th:text="${book.name}"></p>
    <p th:text="${book.price}"></p>
</div>

可見*{...}能夠幫咱們省去不少冗餘的選擇代碼

Link URL Expressions: @{...}

URL在WEB頁面中可謂是錯綜複雜,有各式各樣的URL。並且一旦項目重構,由於上下文的改變極可能形成相對路徑甚至絕對路徑的失效。Thymeleaf將URL歸類爲一下幾種並分別給出了相應的支持。下面給出一些示例:

<a th:href="@{http://www.thymeleaf.org}"/>: 展現絕對路徑 http://www.thymeleaf.org
<a th:href="@{/order/list}"/> : 和上下文相對路徑,若是咱們的項目部署在 <a th:href="@{/order/list}">,那麼等價於 <a href="/myapp/order/list">
<a th:href="@{~/billing-app/showDetails.htm}">: 服務器相對路徑,能夠指向同一個服務器上另外一個上下文的資源,若是咱們的項目部署在 <a th:href="@{/order/list}">,那麼等價於 <a href="/billing-app/showDetails.htm">
<script th:src="@{//scriptserver.example.net/myscript.js}">...</script>: 協議相關路徑,本質上是絕對路徑,會保證協議的一致性,一般用於引入靜態資源如js或css等
<a th:href="@{/order/details(id=3)}">:在URL中添加參數,等價於 <a href="/order/details?id=3">。若是須要傳入多個參數,能夠用逗號隔開
<a th:href="@{/order/{id}/details(id=3,action='show_all')}">:將傳入的參數自動轉化爲路徑變量,這裏等價於 <a href="/order/3/details?action=show_all">
<a th:href="@{/home#all_info(action='show')}">定位到界面中id爲all_info的部分,等價於 <a href="/home?action=show#all_info">
<a th:href="@{'/details/'+${user.login}(orderId=${o.id})}">view</a>URL自己也能夠是一個變量定義的,也一樣容許傳入參數。

Fragment Expressions: ~{...}

容許將HTML代碼塊插入到多個地方。好比咱們常常會須要將HTML頁面分割爲HEADER,SIDEBAR,FOOTER等部分,經過Fragment符號能夠將他們分割成單獨的文件而且插入到須要他們的頁面中。提升了代碼的複用性。它經常和th:insert以及th:replace一塊兒使用。

Literals

text: th:text="'working web application'"用單引號賦值,還支持字符串拼接操做 th:text="'The name of the user is ' + ${user.name}"
numeric: th:text="2013 + 2"
boolean: th:if="${user.isAdmin()} == false">
null: th:if="${variable.something} == null"

Literals Replacement

在上一節提到了字符串拼接操做,這是一個很經常使用的操做。所以Thymeleaf也專門封裝了一個字符串替換符來支持這個操做,所以上面的th:text="'The name of the user is ' + ${user.name}"等價於th:text="|The name of the user is ${user.name}|"從而加強了可讀性。
須要注意的是,替換符||中只會對${...}, *{...}, #{...}進行轉義,其它的都不會進行轉義,所以當遇到如boolean常量時咱們仍是須要使用拼接符將其轉化爲以下格式th:text="${user.isAdmin()}==false + ' ' + |${twovar}, ${threevar}|"

運算符,比較符,條件符

+ - * /(div) %(mod)
gt (>), lt (<), ge (>=), le (<=), not (!) eq (==), neq/ne (!=)
? :
這些都在Thymeleaf具備良好的支持,這裏要強調一個獨特的用法就是
th:text="*{age}?: '(no age specified)'"等價於th:text="*{age != null}? *{age} : '(no age specified)',即?:會自動填入默認值

不進行任何操做_

<span th:text="${user.name} ?: _">no user authenticated</span>
等價於
<span th:text="${user.name} ?: 'no user authenticated'">...</span>
也就是說,當用戶名不存在是,則顯示span標籤中原有的text

預處理 __${expression}__

目前舉例的場景是能夠在預處理階段根據locale決定如何解讀messages。例如如今有兩個地區的.properties文件,能夠在預處理階段根據地區決定使用那個.properties文件。
<p th:text="${__#{article.text('textVar')}__}">Some text here...</p>
若是實在中國地區,就會讀取後綴爲ch.properties的文件中articale.text的內容

th標籤記錄

th:attr: 能夠更改這個所在的標籤的某個的屬性的值,例如 th:attr="action=@{/subscribe}"就將action的屬性改變爲動態生成的@{/subscribe},還容許對多個屬性賦值,每一個屬性之間用逗號隔開,如 <img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

th:attr由於其醜陋而致使極少使用。大多數的HTML標籤Thymeleaf都爲其封裝了專門的賦值th標籤

clipboard.png

clipboard.png

clipboard.png

這是官網上給的具體封裝的標籤例子,基本上HTML已有的標籤都被瘋轉爲th標籤,而且容許你在其中使用Standard Dialect語法。

若是你想對多個th標籤賦予相同的值,Thymeleaf連這種狀況都幫你想好了,你可使用以下語法簡化
th:alt-title="#{logo}"等價於th:alt="#{logo}" th:title="#{logo}"

th:attrappend: 添加值至某個attr,引伸的有 th:classappend, th:styleappend
th:whatever: 這個標籤比較神奇,其實它的本質是自定義任何標籤均可以。直接看例子 <span th:whatever="${user.name}">...</span>等價於 <span whatever="John Apricot">...</span>

目前剛剛整理完畢了Thymeleaf前誤解的內容,會開下一個博客繼續介紹(fanyi)後面的內容。內容尊的好多啊QAQ

Refernces

tymeleaf官網

clipboard.png
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~

相關文章
相關標籤/搜索