SpringBoot整合Thymeleaf


  • Thymeleaf 存放規則
    • 前綴路徑classpath:/templates/
    • 后綴: .html
    • SpringBoot默認前綴和后綴就是 thymeleaf
    • 也就是說把 html 頁面放在resources/templates/ ,thymeleaf 就能自動渲染

 

  • Thymeleaf 用法舉例
    • 在pom中引入thymeleaf依賴
<!-- 引入thymeleaf依賴 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
    • 設置thymeleaf版本
<properties>
  <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
  <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
    • yml配置文件設置thymeleaf屬性
spring: thymeleaf: cache: false prefix: classpath:/templates/ suffix: .html encoding: UTF-8 content-type: text/html mode: HTML5
    • resources/templates/ 中新建 .html 測試文件
<!DOCTYPE HTML>
<!-- 導入thymeleaf -->
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <title>success</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <!-- th:href = '@{/css/success.css}' 中的css前面的 / 不能省略,會報錯 -->
    <link type='text/css' rel='styleSheet' th:href='@{/css/success.css}'/>
    <!-- 使用單引號和雙引號都行 -->
    <script th:src="@{/js/test.js}"></script>
</head>
<body id="body"> <!-- ${ 讀取name元素存放的內容 } }--> <h2 th:text=" 'Hello, My name is ' + ${name}"></h2> </body>
</html>
    • 編寫Controller類跳轉頁面
package com.asimple.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/thymeleaf") public class ThymeleafController { @RequestMapping("/success") public String success(Model model) { //控制台驗證是否執行
        System.out.println("This is success of thymeleaf"); //向前端傳值
        model.addAttribute("name", "XiaoMing"); //跳轉頁面,由於配置了前綴和后綴,相當於是 /templates/success.html
        return "success"; } }

 


免責聲明!

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



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