如何使用SpringBoot+Thymeleaf技術

這篇文章主要講解了“如何使用Spring Boot+Thymeleaf技術”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“如何使用Spring Boot+Thymeleaf技術”吧!

成都一家集口碑和實力的網站建設服務商,擁有專業(yè)的企業(yè)建站團隊和靠譜的建站技術,十余年企業(yè)及個人網站建設經驗 ,為成都上千客戶提供網頁設計制作,網站開發(fā),企業(yè)網站制作建設等服務,包括成都營銷型網站建設,品牌網站制作,同時也為不同行業(yè)的客戶提供成都網站設計、做網站的服務,包括成都電商型網站制作建設,裝修行業(yè)網站制作建設,傳統(tǒng)機械行業(yè)網站建設,傳統(tǒng)農業(yè)行業(yè)網站制作建設。在成都做網站,選網站制作建設服務商就選創(chuàng)新互聯(lián)。

1. Thymeleaf 簡介

Thymeleaf 是新一代 Java 模板引擎,它類似于 Velocity、FreeMarker 等傳統(tǒng) Java 模板引擎,但是與傳統(tǒng) Java 模板引擎不同的是,Thymeleaf 支持 HTML 原型。

它既可以讓前端工程師在瀏覽器中直接打開查看樣式,也可以讓后端工程師結合真實數據查看顯示效果,同時,SpringBoot 提供了 Thymeleaf 自動化配置解決方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。

事實上, Thymeleaf 除了展示基本的 HTML ,進行頁面渲染之外,也可以作為一個 HTML 片段進行渲染,例如我們在做郵件發(fā)送時,可以使用 Thymeleaf 作為郵件發(fā)送模板。

另外,由于 Thymeleaf 模板后綴為 .html,可以直接被瀏覽器打開,因此,預覽時非常方便。

2. 整合 Spring Boot

2.1 基本用法

Spring Boot 中整合 Thymeleaf 非常容易,只需要創(chuàng)建項目時添加 Thymeleaf 即可:

如何使用Spring Boot+Thymeleaf技術

創(chuàng)建完成后,pom.xml 依賴如下:

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-thymeleaf</artifactid>
</dependency>
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-web</artifactid>
</dependency>

當然,Thymeleaf 不僅僅能在 Spring Boot 中使用,也可以使用在其他地方,只不過 Spring Boot 針對 Thymeleaf 提供了一整套的自動化配置方案,這一套配置類的屬性在 org.springframework.boot.autoconfigure.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";
        private boolean checkTemplate = true;
        private boolean checkTemplateLocation = true;
        private String prefix = DEFAULT_PREFIX;
        private String suffix = DEFAULT_SUFFIX;
        private String mode = "HTML";
        private Charset encoding = DEFAULT_ENCODING;
        private boolean cache = true;
        //...
}
  1. 首先通過 @ConfigurationProperties 注解,將 application.properties 前綴為 spring.thymeleaf 的配置和這個類中的屬性綁定。

  2. 前三個 static 變量定義了默認的編碼格式、視圖解析器的前綴、后綴等。

  3. 從前三行配置中,可以看出來,Thymeleaf 模板的默認位置在 resources/templates 目錄下,默認的后綴是 html

  4. 這些配置,如果開發(fā)者不自己提供,則使用 默認的,如果自己提供,則在 application.properties 中以 spring.thymeleaf 開始相關的配置。

而我們剛剛提到的,Spring Boot 為 Thymeleaf 提供的自動化配置類,則是 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration ,部分源碼如下:

@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}

可以看到,在這個自動化配置類中,首先導入 ThymeleafProperties ,然后 @ConditionalOnClass 注解表示當當前系統(tǒng)中存在 TemplateModeSpringTemplateEngine 類時,當前的自動化配置類才會生效,即只要項目中引入了 Thymeleaf 相關的依賴,這個配置就會生效。

這些默認的配置我們幾乎不需要做任何更改就可以直接使用了。如果開發(fā)者有特殊需求,則可以在 application.properties 中配置以 spring.thymeleaf 開頭的屬性即可。

接下來我們就可以創(chuàng)建 Controller 了,實際上引入 Thymeleaf 依賴之后,我們可以不做任何配置。新建的 IndexController 如下:

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index(Model model) {
        List<user> users = new ArrayList&lt;&gt;();
        for (int i = 0; i &lt; 10; i++) {
            User u = new User();
            u.setId((long) i);
            u.setName("javaboy:" + i);
            u.setAddress("深圳:" + i);
            users.add(u);
        }
        model.addAttribute("users", users);
        return "index";
    }
}
public class User {
    private Long id;
    private String name;
    private String address;
    //省略 getter/setter
}

IndexController 中返回邏輯視圖名+數據,邏輯視圖名為 index ,意思我們需要在 resources/templates 目錄下提供一個名為 index.htmlThymeleaf 模板文件。

  • 創(chuàng)建 Thymeleaf

<meta charset="UTF-8">
    <title>Title</title>


<table border="1">
    <tbody><tr>
        <td>編號</td>
        <td>用戶名</td>
        <td>地址</td>
    </tr>
    <tr th:each="user : ${users}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${user.address}"></td>
    </tr>
</tbody></table>

Thymeleaf 中,通過 th:each 指令來遍歷一個集合,數據的展示通過 th:text 指令來實現,

注意 index.html 最上面引入 thymeleaf 名稱空間(最新版并無強制要求)。

配置完成后,就可以啟動項目了,訪問 /index 接口,就能看到集合中的數據了:

如何使用Spring Boot+Thymeleaf技術

2.2 手動渲染

前面我們說的是返回一個 Thymeleaf 模板,我們也可以手動渲染 Thymeleaf 模板,這個一般在郵件發(fā)送時候有用,例如我在 resources/templates 目錄下新建一個郵件模板,如下:

<meta charset="UTF-8">
    <title>Title</title>


<p>hello 歡迎 <span th:text="${username}"></span>加入 XXX 集團,您的入職信息如下:</p>
<table border="1">
    <tbody><tr>
        <td>職位</td>
        <td th:text="${position}"></td>
    </tr>
    <tr>
        <td>薪水</td>
        <td th:text="${salary}"></td>
    </tr>
</tbody></table>
<img src="https://oscimg.oschina.net/oscnet/javaboy.jpg" alt="">

這一個 HTML 模板中,有幾個變量,我們要將這個 HTML 模板渲染成一個 String 字符串,再把這個字符串通過郵件發(fā)送出去,那么如何手動渲染呢?

@Autowired
TemplateEngine templateEngine;
@Test
public void test1() throws MessagingException {
    Context context = new Context();
    context.setVariable("username", "javaboy");
    context.setVariable("position", "Java工程師");
    context.setVariable("salary", 99999);
    String mail = templateEngine.process("mail", context);
    //省略郵件發(fā)送
}
  1. 渲染時,我們需要首先注入一個 TemplateEngine 對象,這個對象就是在 Thymeleaf 的自動化配置類中配置的(即當我們引入 Thymeleaf 的依賴之后,這個實例就有了)。

  2. 然后構造一個 Context 對象用來存放變量。

  3. 調用 process 方法進行渲染,該方法的返回值就是渲染后的 HTML 字符串,然后我們將這個字符串發(fā)送出去。

3. Thymeleaf 細節(jié)

前面兩個案例讓小伙伴們大致上理解了在 Spring Boot 中要如何使用 Thymeleaf,接下來,松哥將詳細介紹 Thymeleaf 本身的一些具體用法。

3.1 標準表達式語法

3.1.1 簡單表達式

${...}

直接使用 th:xx = "${}" 獲取對象屬性。這個在前面的案例中已經演示過了,不再贅述。

*{...}

可以像 ${...} 一樣使用,也可以通過 th:object 獲取對象,然后使用 th:xx = "*{}" 獲取對象屬性,這種簡寫風格極為清爽,推薦大家在實際項目中使用。

<table border="1" th:object="${user}">
<tbody><tr>
    <td>用戶名</td>
    <td th:text="*{username}"></td>
</tr>
<tr>
    <td>地址</td>
    <td th:text="*{address}"></td>
</tr>
</tbody></table>

#{...}

通常的國際化屬性:#{...} 用于獲取國際化語言翻譯值。

在 resources 目錄下新建兩個文件:messages.properties 和 messages_zh_CN.properties,內容如下:

messages.properties:

message = javaboy

messages_zh_CN.properties:

message = 江南一點雨

然后在 thymeleaf 中引用 message,系統(tǒng)會根據瀏覽器的語言環(huán)境顯示不同的值:

<div th:text="#{message}"></div>

@{...}

  • 引用絕對 URL:

<script type="text/javascript" th:src="@{http://localhost:8080/hello.js}"></script>

等價于:

<script type="text/javascript" src="http://localhost:8080/hello.js"></script>
  • 上下文相關的 URL:

首先在 application.properties 中配置 Spring Boot 的上下文,以便于測試:

server.servlet.context-path=/myapp

引用路徑:

<script type="text/javascript" th:src="@{/hello.js}"></script>

等價于:

<script type="text/javascript" src="/myapp/hello.js"></script>
  • 相對 URL:

這個相對是指相對于服務器的 URL,例如如下引用:

<script type="text/javascript" th:src="@{~/hello.js}"></script>

等價于:

<script type="text/javascript" src="/hello.js"></script>

應用程序的上下文 /myapp將被忽略。

  • 協(xié)議相對 URL:

<script type="text/javascript" th:src="@{//localhost:8080/hello.js}"></script>

等價于:

<script type="text/javascript" src="//localhost:8080/hello.js"></script>
  • 帶參數的 URL:

<script type="text/javascript" th:src="@{//localhost:8080/hello.js(name='javaboy',age=99)}"></script>

等價于:

<script type="text/javascript" th:src="//localhost:8080/hello.js?name=javaboy&amp;age=99"></script>

~{...}

片段表達式是 Thymeleaf 的特色之一,細粒度可以達到標簽級別,這是 JSP 無法做到的。片段表達式擁有三種語法:

  • ~{ viewName }:表示引入完整頁面

  • ~{ viewName ::selector}:表示在指定頁面尋找片段,其中 selector 可為片段名、jquery選擇器等

  • ~{ ::selector}: 表示在當前頁尋找

舉個簡單例子。

在 resources/templates 目錄下新建 my_fragment.html 文件,內容如下:

<div th:fragment="javaboy_link"><a href="http://www.javaboy.org">www.javaboy</a></div>
<div th:fragment="itboyhub_link"><a href="http://www.itboyhub.com">www.itboyhub.com</a></div>

這里有兩個 div,通過 th:fragment 來定義片段,兩個 div 分別具有不同的名字。

然后在另外一個頁面中引用該片段:

<table border="1" th:object="${user}" th:fragment="aaa">
<tbody><tr>
    <td>用戶名</td>
    <td th:text="*{username}"></td>
</tr>
<tr>
    <td>地址</td>
    <td th:text="*{address}"></td>
</tr>
</tbody></table>
<hr>
<div th:replace="my_fragment.html"></div>
<hr>
<div th:replace="~{my_fragment.html::javaboy_link}"></div>
<hr>
<div th:replace="~{::aaa}"></div>

通過 th:replace 來引用片段。第一個表示引用完整的 my_fragment.html 頁面;第二個表示引用 my_fragment.html 中的名為 javaboy_link 的片段;第三個表示引用當前頁面名為 aaa 的片段,也就是上面那個 table。

3.1.2 字面量

這些是一些可以直接寫在表達式中的字符,主要有如下幾種:

  • 文本字面量: 'one text', 'Another one!',…

  • 數字字面量: 0, 34, 3.0, 12.3,…

  • 布爾字面量: true, false

  • Null字面量: null

  • 字面量標記:one, sometext, main,…

案例:

<div th:text="'這是 文本字面量(有空格)'"></div>
<div th:text="javaboy"></div>
<div th:text="99"></div>
<div th:text="true"></div>

如果文本是英文,并且不包含空格、逗號等字符,可以不用加單引號。

3.1.3 文本運算

文本可以使用 + 進行拼接。

<div th:text="'hello '+'javaboy'"></div>
<div th:text="'hello '+${user.username}"></div>

如果字符串中包含變量,也可以使用另一種簡單的方式,叫做字面量置換,用 | 代替 '...' + '...',如下:

<div th:text="|hello ${user.username}|"></div>
<div th:text="'hello '+${user.username}+' '+|Go ${user.address}|"></div>
3.1.4 算術運算

算術運算有:+, -, *, /%

<div th:with="age=(99*99/99+99-1)">
    <div th:text="${age}"></div>
</div>

th:with 定義了一個局部變量 age,在其所在的 div 中可以使用該局部變量。

3.1.5 布爾運算
  • 二元運算符:and, or

  • 布爾非(一元運算符):!, not

案例:

<div th:with="age=(99*99/99+99-1)">
    <div th:text="9 eq 9 or 8 ne 8"></div>
    <div th:text="!(9 eq 9 or 8 ne 8)"></div>
    <div th:text="not(9 eq 9 or 8 ne 8)"></div>
</div>
3.1.6 比較和相等

表達式里的值可以使用 &gt;, &lt;, &gt;=&lt;= 符號比較。==!= 運算符用于檢查相等(或者不相等)。注意 XML規(guī)定 &lt;&gt; 標簽不能用于屬性值,所以應當把它們轉義為 &lt;&gt;。

如果不想轉義,也可以使用別名:gt (>);lt (<);ge (>=);le (<=);not (!)。還有 eq (==), neq/ne (!=)。

舉例:

<div th:with="age=(99*99/99+99-1)">
    <div th:text="${age} eq 197"></div>
    <div th:text="${age} ne 197"></div>
    <div th:text="${age} ge 197"></div>
    <div th:text="${age} gt 197"></div>
    <div th:text="${age} le 197"></div>
    <div th:text="${age} lt 197"></div>
</div>
3.1.7 條件運算符

類似于我們 Java 中的三目運算符。

<div th:with="age=(99*99/99+99-1)">
    <div th:text="(${age} ne 197)?'yes':'no'"></div>
</div>

其中,: 后面的部分可以省略,如果省略了,又同時計算結果為 false 時,將返回 null。

3.1.8 內置對象

基本內置對象:

  • #ctx:上下文對象。

  • #vars: 上下文變量。

  • #locale:上下文區(qū)域設置。

  • #request:(僅在 Web 上下文中)HttpServletRequest 對象。

  • #response:(僅在 Web 上下文中)HttpServletResponse 對象。

  • #session:(僅在 Web 上下文中)HttpSession 對象。

  • #servletContext:(僅在 Web 上下文中)ServletContext 對象。

在頁面可以訪問到上面這些內置對象,舉個簡單例子:

<div th:text="${#session.getAttribute(&quot;name&quot;)}"></div>

實用內置對象:

  • #execInfo:有關正在處理的模板的信息。

  • #messages:在變量表達式中獲取外部化消息的方法,與使用#{...}語法獲得的方式相同。

  • #uris:轉義URL / URI部分的方法

  • #conversions:執(zhí)行配置的轉換服務(如果有)的方法。

  • #dates:java.util.Date對象的方法:格式化,組件提取等

  • #calendars:類似于#dates但是java.util.Calendar對象。

  • #numbers:用于格式化數字對象的方法。

  • #strings:String對象的方法:contains,startsWith,prepending / appending等

  • #objects:一般對象的方法。

  • #bools:布爾評估的方法。

  • #arrays:數組方法。

  • #lists:列表的方法。

  • #sets:集合的方法。

  • #maps:地圖方法。

  • #aggregates:在數組或集合上創(chuàng)建聚合的方法。

  • #ids:處理可能重復的id屬性的方法(例如,作為迭代的結果)。

這是一些內置對象以及工具方法,使用方式也都比較容易,如果使用的是 IntelliJ IDEA,都會自動提示對象中的方法,很方便。

舉例:

<div th:text="${#execInfo.getProcessedTemplateName()}"></div>
<div th:text="${#arrays.length(#request.getAttribute('names'))}"></div>

3.2 設置屬性值

這個是給 HTML 元素設置屬性值??梢砸淮卧O置多個,多個之間用 , 分隔開。

例如:

<img th:attr="src=@{/1.png},title=${user.username},alt=${user.username}" src="">

會被渲染成:

<img src="/myapp/1.png" title="javaboy" alt="javaboy">

當然這種設置方法不太美觀,可讀性也不好。Thymeleaf 還支持在每一個原生的 HTML 屬性前加上 th: 前綴的方式來使用動態(tài)值,像下面這樣:

<img th:src="@{/1.png}" th:alt="${user.username}" th:title="${user.username}" src="">

這種寫法看起來更清晰一些,渲染效果和前面一致。

上面案例中的 alt 和 title 則是兩個特殊的屬性,可以一次性設置,像下面這樣:

<img th:src="@{/1.png}" th:alt-title="${user.username}" src="">

這個等價于前文的設置。

3.3 遍歷

數組/集合/Map/Enumeration/Iterator 等的遍歷也算是一個非常常見的需求,Thymeleaf 中通過 th:each 來實現遍歷,像下面這樣:

<table border="1">
    <tbody><tr th:each="u : ${users}">
        <td th:text="${u.username}"></td>
        <td th:text="${u.address}"></td>
    </tr>
</tbody></table>

users 是要遍歷的集合/數組,u 則是集合中的單個元素。

遍歷的時候,我們可能需要獲取遍歷的狀態(tài),Thymeleaf 也對此提供了支持:

  • index:當前的遍歷索引,從0開始。

  • count:當前的遍歷索引,從1開始。

  • size:被遍歷變量里的元素數量。

  • current:每次遍歷的遍歷變量。

  • even/odd:當前的遍歷是偶數次還是奇數次。

  • first:當前是否為首次遍歷。

  • last:當前是否為最后一次遍歷。

u 后面的 state 表示遍歷狀態(tài),通過遍歷狀態(tài)可以引用上面的屬性。

<table border="1">
    <tbody><tr th:each="u,state : ${users}">
        <td th:text="${u.username}"></td>
        <td th:text="${u.address}"></td>
        <td th:text="${state.index}"></td>
        <td th:text="${state.count}"></td>
        <td th:text="${state.size}"></td>
        <td th:text="${state.current}"></td>
        <td th:text="${state.even}"></td>
        <td th:text="${state.odd}"></td>
        <td th:text="${state.first}"></td>
        <td th:text="${state.last}"></td>
    </tr>
</tbody></table>

3.4 分支語句

只顯示奇數次的遍歷,可以使用 th:if,如下:

<table border="1">
    <tbody><tr th:each="u,state : ${users}" th:if="${state.odd}">
        <td th:text="${u.username}"></td>
        <td th:text="${u.address}"></td>
        <td th:text="${state.index}"></td>
        <td th:text="${state.count}"></td>
        <td th:text="${state.size}"></td>
        <td th:text="${state.current}"></td>
        <td th:text="${state.even}"></td>
        <td th:text="${state.odd}"></td>
        <td th:text="${state.first}"></td>
        <td th:text="${state.last}"></td>
    </tr>
</tbody></table>

th:if 不僅僅只接受布爾值,也接受其他類型的值,例如如下值都會判定為 true:

  • 如果值是布爾值,并且為 true。

  • 如果值是數字,并且不為 0。

  • 如果值是字符,并且不為 0。

  • 如果值是字符串,并且不為 “false”, “off” 或者 “no”。

  • 如果值不是布爾值,數字,字符或者字符串。

但是如果值為 null,th:if 會求值為 false。

th:unless 的判定條件則與 th:if 完全相反。

<table border="1">
    <tbody><tr th:each="u,state : ${users}" th:unless="${state.odd}">
        <td th:text="${u.username}"></td>
        <td th:text="${u.address}"></td>
        <td th:text="${state.index}"></td>
        <td th:text="${state.count}"></td>
        <td th:text="${state.size}"></td>
        <td th:text="${state.current}"></td>
        <td th:text="${state.even}"></td>
        <td th:text="${state.odd}"></td>
        <td th:text="${state.first}"></td>
        <td th:text="${state.last}"></td>
    </tr>
</tbody></table>

這個顯示效果則與上面的完全相反。

當可能性比較多的時候,也可以使用 switch:

<table border="1">
    <tbody><tr th:each="u,state : ${users}">
        <td th:text="${u.username}"></td>
        <td th:text="${u.address}"></td>
        <td th:text="${state.index}"></td>
        <td th:text="${state.count}"></td>
        <td th:text="${state.size}"></td>
        <td th:text="${state.current}"></td>
        <td th:text="${state.even}"></td>
        <td th:text="${state.odd}"></td>
        <td th:text="${state.first}"></td>
        <td th:text="${state.last}"></td>
        <td th:switch="${state.odd}">
            <span th:case="true">odd</span>
            <span th:case="*">even</span>
        </td>
    </tr>
</tbody></table>

th:case="*" 則表示默認選項。

3.5 本地變量

這個我們前面已經涉及到了,使用 th:with 可以定義一個本地變量。

3.6 內聯(lián)

我們可以使用屬性將數據放入頁面模版中,但是很多時候,內聯(lián)的方式看起來更加直觀一些,像下面這樣:

<div>hello [[${user.username}]]</div>

用內聯(lián)的方式去做拼接也顯得更加自然。

[[...]] 對應于 th:text (結果會是轉義的 HTML),[(...)]對應于 th:utext,它不會執(zhí)行任何的 HTML 轉義。

像下面這樣:

<div th:with="str='hello <strong>javaboy</strong>'">
    <div>[[${str}]]</div>
    <div>[(${str})]</div>
</div>

最終的顯示效果如下:

如何使用Spring Boot+Thymeleaf技術

不過內聯(lián)方式有一個問題。我們使用 Thymeleaf 的一大優(yōu)勢在于不用動態(tài)渲染就可以直接在瀏覽器中看到顯示效果,當我們使用屬性配置的時候確實是這樣,但是如果我們使用內聯(lián)的方式,各種表達式就會直接展示在靜態(tài)網頁中。

也可以在 js 或者 css 中使用內聯(lián),以 js 為例,使用方式如下:

<script th:inline="javascript">
    var username=[[${user.username}]]
    console.log(username)
</script>

js 中需要通過 th:inline="javascript" 開啟內聯(lián)。

感謝各位的閱讀,以上就是“如何使用Spring Boot+Thymeleaf技術”的內容了,經過本文的學習后,相信大家對如何使用Spring Boot+Thymeleaf技術這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關知識點的文章,歡迎關注!

網站欄目:如何使用SpringBoot+Thymeleaf技術
網頁URL:http://muchs.cn/article36/jojjsg.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供手機網站建設、網站收錄、網站維護、網站設計、定制開發(fā)、營銷型網站建設

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

h5響應式網站建設