<noframes id="bhrfl"><address id="bhrfl"></address>

    <address id="bhrfl"></address>

    <noframes id="bhrfl"><address id="bhrfl"><th id="bhrfl"></th></address>

    <form id="bhrfl"><th id="bhrfl"><progress id="bhrfl"></progress></th></form>

    <em id="bhrfl"><span id="bhrfl"></span></em>

    全部
    常見問題
    產品動態
    精選推薦

    Spring Boot 2.x基礎教程:使用 Thymeleaf開發Web頁面

    管理 管理 編輯 刪除

    接下來,我們就來具體講講在Spring Boot應用中,如何使用Thymeleaf模板引擎開發Web頁面類的應用。

    #靜態資源訪問

    在我們開發Web應用的時候,需要引用大量的js、css、圖片等靜態資源。Spring Boot默認提供靜態資源目錄位置需置于classpath下,目錄名需符合如下規則:

    • /static
    • /public
    • /resources
    • /META-INF/resources

    舉例:我們可以在src/main/resources/目錄下創建static,在該位置放置一個圖片文件。啟動程序后,嘗試訪問http://localhost:8080/D.jpg。如能顯示圖片,配置成功。

    #渲染Web頁面

    在之前的示例中,我們都是通過@RestController來處理請求,所以返回的內容為json對象。那么如果需要渲染html頁面的時候,要如何實現呢?

    #模板引擎

    在動態HTML實現上Spring Boot依然可以完美勝任,并且提供了多種模板引擎的默認配置支持,所以在推薦的模板引擎下,我們可以很快的上手開發動態網站。

    Spring Boot提供了自動化配置模塊的模板引擎主要有以下幾種:

    • Thymeleaf
    • FreeMarker
    • Groovy

    當你使用上述模板引擎中的任何一個,它們默認的模板配置路徑為:src/main/resources/templates。當然也可以修改這個路徑,具體如何修改,可在后續各模板引擎的配置屬性中查詢并修改。

    補充:Spring Boot從一開始就建議使用模板引擎,避免使用JSP。同時,隨著Spring Boot版本的迭代,逐步的淘汰了一些較為古老的模板引擎。

    #Thymeleaf

    Thymeleaf是本文我們將具體介紹使用的模板引擎。它是一個XML/XHTML/HTML5模板引擎,可用于Web與非Web環境中的應用開發。它是一個開源的Java庫,基于Apache License 2.0許可,由Daniel Fernández創建,該作者還是Java加密庫Jasypt的作者。

    Thymeleaf提供了一個用于整合Spring MVC的可選模塊,在應用開發中,你可以使用Thymeleaf來完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目標在于提供一種可被瀏覽器正確顯示的、格式良好的模板創建方式,因此也可以用作靜態建模。你可以使用它創建經過驗證的XML與HTML模板。相對于編寫邏輯或代碼,開發者只需將標簽屬性添加到模板中即可。接下來,這些標簽屬性就會在DOM(文檔對象模型)上執行預先制定好的邏輯。

    示例模板:

    <table>
      <thead>
        <tr>
          <th th:text="#{msgs.headers.name}">Name</td>
          <th th:text="#{msgs.headers.price}">Price</td>
        </tr>
      </thead>
      <tbody>
        <tr th:each="prod : ${allProducts}">
          <td th:text="${prod.name}">Oranges</td>
          <td th:text="${#numbers.formatDecimal(prod.price,1,2)}">0.99</td>
        </tr>
      </tbody>
    </table>
    

    可以看到Thymeleaf主要以屬性的方式加入到html標簽中,瀏覽器在解析html時,當檢查到沒有的屬性時候會忽略,所以Thymeleaf的模板可以通過瀏覽器直接打開展現,這樣非常有利于前后端的分離。

    #動手試一下

    第一步:新建一個Spring Boot應用,在pom.xml中加入所需的模板引擎模塊,比如使用thymeleaf的話,只需要引入下面依賴:

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

    第二步:創建一個Spring MVC的傳統Controller,用來處理根路徑的請求,將解決渲染到index頁面上,具體實現如下

    @Controller
    public class HelloController {
    
        @GetMapping("/")
        public String index(ModelMap map) {
            map.addAttribute("host", "https://blog.didispace.com");
            return "index";
        }
    
    }
    

    簡要說明:

    • 在渲染到index頁面的時候,通過ModelMap,往頁面中增加一個host參數,其值為https://blog.didispace.com
    • return的值index代表了要使用的模板頁面名稱,默認情況下,它將對應到src/main/resources/templates/目錄下的index.html模板頁面

    第三步:根據上一步要映射的模板,去模板路徑src/main/resources/templates下新建模板文件index.html,內容如下:


    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8" />
        <title></title>
    </head>
    <body>
    <h1 th:text="${host}">Hello World</h1>
    </body>
    </html>

    在該頁面的body中,包含了一個帶有Thymeleaf屬性的h1標簽,該便簽內容將綁定host參數的值。

    由于Thymeleaf通過屬性綁定的特性。該模板頁面同其他模板引擎不同,直接通過瀏覽器打開html頁面,它是可以正常運作的,將會直接展現Hello World標題。這有利于開發頁面的時候可以在非啟動環境下驗證應前端樣式的正確性。

    如果啟動程序后,訪問http://localhost:8080/,上面頁面就會展示Controller中host的值:https://blog.didispace.com,做到了不破壞HTML自身內容的數據邏輯分離。

    更多Thymeleaf的頁面語法,可以訪問Thymeleaf的官方文檔來深入學習使用。

    #Thymeleaf的配置參數

    如有需要修改默認配置的時候,只需復制下面要修改的屬性到application.properties中,并修改成需要的值:


    # Enable template caching.
    spring.thymeleaf.cache=true 
    # Check that the templates location exists.
    spring.thymeleaf.check-template-location=true 
    # Content-Type value.
    spring.thymeleaf.content-type=text/html 
    # Enable MVC Thymeleaf view resolution.
    spring.thymeleaf.enabled=true 
    # Template encoding.
    spring.thymeleaf.encoding=UTF-8 
    # Comma-separated list of view names that should be excluded from resolution.
    spring.thymeleaf.excluded-view-names= 
    # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
    spring.thymeleaf.mode=HTML5 
    # Prefix that gets prepended to view names when building a URL.
    spring.thymeleaf.prefix=classpath:/templates/ 
    # Suffix that gets appended to view names when building a URL.
    spring.thymeleaf.suffix=.html  spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
    

    舉幾個我們常用的配置內容:

    Q:不想每次修改頁面都重啟

    A:修改spring.thymeleaf.cache參數,設置為false

    Q:不想使用template目錄存放模板文件

    A:修改spring.thymeleaf.prefix參數,設置為你想放置模板文件的目錄

    Q:不想使用index作為模板文件的擴展名

    A:修改spring.thymeleaf.suffix參數,設置為你想用的擴展名

    Q:HTML5的嚴格校驗很煩人

    A:修改spring.thymeleaf.mode參數,設置為LEGACYHTML5

    更多本系列免費教程連載「點擊進入匯總目錄」

    #代碼示例

    本文的相關例子可以查看下面倉庫中的chapter4-1目錄:

    請登錄后查看

    CRMEB 最后編輯于2025-02-27 14:48:27

    快捷回復
    回復
    回復
    回復({{post_count}}) {{!is_user ? '我的回復' :'全部回復'}}
    排序 默認正序 回復倒序 點贊倒序

    {{item.user_info.nickname ? item.user_info.nickname : item.user_name}} LV.{{ item.user_info.bbs_level }}

    作者 管理員 企業

    {{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest == 1? '取消推薦': '推薦'}}
    {{item.is_suggest == 1? '取消推薦': '推薦'}}
    沙發 板凳 地板 {{item.floor}}#
    {{item.user_info.title || '暫無簡介'}}
    附件

    {{itemf.name}}

    {{item.created_at}}  {{item.ip_address}}
    {{item.like_count}}
    {{item.showReply ? '取消回復' : '回復'}}
    刪除
    回復
    回復

    {{itemc.user_info.nickname}}

    {{itemc.user_name}}

    回復 {{itemc.comment_user_info.nickname}}

    附件

    {{itemf.name}}

    {{itemc.created_at}}
    {{itemc.like_count}}
    {{itemc.showReply ? '取消回復' : '回復'}}
    刪除
    回復
    回復
    查看更多
    948
    {{like_count}}
    {{collect_count}}
    添加回復 ({{post_count}})

    相關推薦

    快速安全登錄

    使用微信掃碼登錄
    {{item.label}} 加精
    {{item.label}} {{item.label}} 板塊推薦 常見問題 產品動態 精選推薦 首頁頭條 首頁動態 首頁推薦
    取 消 確 定
    回復
    回復
    問題:
    問題自動獲取的帖子內容,不準確時需要手動修改. [獲取答案]
    答案:
    提交
    bug 需求 取 消 確 定

    微信登錄/注冊

    切換手機號登錄

    {{ bind_phone ? '綁定手機' : '手機登錄'}}

    {{codeText}}
    切換微信登錄/注冊
    暫不綁定
    亚洲欧美字幕
    CRMEB客服

    CRMEB咨詢熱線 咨詢熱線

    400-8888-794

    微信掃碼咨詢

    CRMEB開源商城下載 源碼下載 CRMEB幫助文檔 幫助文檔
    返回頂部 返回頂部
    CRMEB客服