Spring Boot - Thymeleaf



Thymeleaf 是一個基於 Java 的庫,用於建立 Web 應用程式。它為在 Web 應用程式中提供 XHTML/HTML5 提供了良好的支援。在本章中,您將詳細瞭解 Thymeleaf。

Thymeleaf 模板

Thymeleaf 將您的檔案轉換為格式良好的 XML 檔案。它包含以下 6 種類型的模板:

  • XML
  • 有效 XML
  • XHTML
  • 有效 XHTML
  • HTML5
  • 傳統 HTML5

除傳統 HTML5 外,所有模板都指的是格式良好的有效 XML 檔案。傳統 HTML5 允許我們在網頁中呈現 HTML5 標籤,包括未關閉的標籤。

Web 應用程式

您可以使用 Thymeleaf 模板在 Spring Boot 中建立 Web 應用程式。您需要按照以下步驟使用 Thymeleaf 在 Spring Boot 中建立 Web 應用程式。

使用以下程式碼建立一個 @Controller 類檔案,將請求 URI 重定向到 HTML 檔案:

WebController.java

package com.tutorialspoint.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class WebController {
   @GetMapping(value = "/index")
   public String index() {
      return "index";
   }
}

在上面的示例中,請求 URI 為 /index,並且控制權被重定向到 index.html 檔案。請注意,index.html 檔案應放在 templates 目錄下,所有 JS 和 CSS 檔案應放在類路徑的 static 目錄下。在所示示例中,我們使用 CSS 檔案更改文字的顏色。

您可以使用以下程式碼並在單獨的資料夾 css 中建立一個 CSS 檔案,並將檔案命名為 styles.css:

h4 {
   color: red;
}

index.html 檔案的程式碼如下:

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1" />
      <link href = "css/styles.css" rel = "stylesheet"/>
      <title>Spring Boot Application</title>
   </head>
   <body>
      <h4>Welcome to Thymeleaf Spring Boot web application</h4>
   </body>
</html>

專案資源管理器在下面給出的螢幕截圖中顯示:

Project Explorer Screenshot

現在,我們需要在構建配置檔案中新增 Spring Boot Starter Thymeleaf 依賴項。

Maven 使用者可以將以下依賴項新增到 pom.xml 檔案中:

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

Gradle 使用者可以在 build.gradle 檔案中新增以下依賴項:

compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'

主 Spring Boot 應用程式類檔案的程式碼如下:

DemoApplication.java

package com.tutorialspoint.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

Maven – pom.xml 的程式碼如下:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
   <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>3.3.3</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>
   <url/>
   <licenses>
      <license/>
   </licenses>
   <developers>
      <developer/>
   </developers>
   <scm>
      <connection/>
      <developerConnection/>
      <tag/>
      <url/>
   </scm>
   <properties>
      <java.version>21</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

Gradle – build.gradle 的程式碼如下:

buildscript {
   ext {
      springBootVersion = '3.3.3'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 21

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

您可以建立一個可執行的 JAR 檔案,並使用以下 Maven 或 Gradle 命令執行 Spring Boot 應用程式:

對於 Maven,請使用以下所示的命令:

mvn clean install

“BUILD SUCCESS”後,您可以在 target 目錄下找到 JAR 檔案。

對於 Gradle,請使用以下所示的命令:

gradle clean build

“BUILD SUCCESSFUL”後,您可以在 build/libs 目錄下找到 JAR 檔案。

使用此處提供的命令執行 JAR 檔案:

java –jar <JARFILE> 

現在,應用程式已在 Tomcat 埠 8080 上啟動,如下所示:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

[32m :: Spring Boot :: [39m              [2m (v3.3.3)[0;39m

[2024-09-06T12:48:19Z] [org.springframework.boot.StartupInfoLogger] [main] [50] [INFO ] Starting DemoApplication using Java 21.0.3 with PID 7388 (E:\Dev\demo\target\classes started by Tutorialspoint in E:\Dev\demo)
[2024-09-06T12:48:19Z] [org.springframework.boot.SpringApplication] [main] [654] [INFO ] No active profile set, falling back to 1 default profile: "default"
[2024-09-06T12:48:20Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [111] [INFO ] Tomcat initialized with port 8080 (http)
[2024-09-06T12:48:20Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Initializing ProtocolHandler ["http-nio-8080"]
[2024-09-06T12:48:20Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting service [Tomcat]
[2024-09-06T12:48:20Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting Servlet engine: [Apache Tomcat/10.1.28]
[2024-09-06T12:48:20Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Initializing Spring embedded WebApplicationContext
[2024-09-06T12:48:20Z] [org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext] [main] [296] [INFO ] Root WebApplicationContext: initialization completed in 1033 ms
[2024-09-06T12:48:20Z] [org.springframework.boot.autoconfigure.web.servlet.WelcomePageHandlerMapping] [main] [59] [INFO ] Adding welcome page template: index
[2024-09-06T12:48:21Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting ProtocolHandler ["http-nio-8080"]
[2024-09-06T12:48:21Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [243] [INFO ] Tomcat started on port 8080 (http) with context path '/'
[2024-09-06T12:48:21Z] [org.springframework.boot.StartupInfoLogger] [main] [56] [INFO ] Started DemoApplication in 2.0 seconds (process running for 2.983)

現在在您的 Web 瀏覽器中點選 URL,您將看到如下所示的輸出:

https://:8080/index

Spring Boot Thymleaf web Application
廣告

© . All rights reserved.