Thymeleaf是一個基於Java的庫,用於建立Web應用程式。 它為在Web應用程式中提供XHTML/HTML5提供了很好的支援。 在本章中將詳細了解和學習Thymeleaf。
Thymeleaf將檔案轉換為格式良好的XML檔案。它包含6種型別的模板,如下所示 -
除舊版HTML5之外的所有模板都指的是格式正確的有效XML檔案。 舊版HTML5允許我們在網頁中呈現HTML5標記,包括非封閉標記。
使用Thymeleaf模板在Spring Boot中建立Web應用程式。必須按照以下步驟使用Thymeleaf在Spring Boot中建立Web應用程式。
使用以下程式碼建立@Controller
類檔案以將Request URI重定向到HTML檔案 -
package com.yiibai.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WebController {
@RequestMapping(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 = "UTF-8" />
<link href = "css/styles.css" rel = "stylesheet"/>
<title>Spring Boot應用程式(Tw511.com)</title>
</head>
<body>
<h4>Thymeleaf Spring Boot web應用程式範例</h4>
<p>
Power by Tw511.com
</p>
</body>
</html>
在Eclipse專案瀏覽器顯示,如下面給出的截圖 -
現在,需要在構建組態檔案中新增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應用程式類檔案的程式碼如下 -
package com.yiibai.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 的程式碼如下 -
<?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
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yiibai</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</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 = '1.5.8.RELEASE'
}
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.yiibai'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
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」之後,在目標目錄下找到JAR檔案。
對於Gradle,使用如下所示的命令 -
gradle clean build
在「BUILD SUCCESSFUL」之後,在build/libs 目錄下找到JAR檔案。
使用此處給出的命令執行JAR檔案 -
D:\worksp\springboot\thymeleaf\target>java -jar demo-0.0.1-SNAPSHOT.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.8.RELEASE)
2018-10-04 10:37:55.985 INFO 14820 --- [ main] com.yiibai.demo.DemoApplication : Starting DemoApplication v0.0.1-SNAPSHOT on DESKTOP-CAN8JLM with PID 14820 (D:\worksp\springboot\thymeleaf\target\demo-0.0.1-SNAPSHOT.jar started by hema in D:\worksp\springboot\thymeleaf\target)
2018-10-04 10:37:55.989 INFO 14820 --- [ main] com.yiibai.demo.DemoApplication : No active profile set, falling back to default profiles: default
2018-10-04 10:37:56.498 INFO 14820 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@443b7951: startup date [Thu Oct 04 10:37:56 CST 2018]; root of context hierarchy
2018-10-04 10:37:58.322 INFO 14820 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-10-04 10:37:58.342 INFO 14820 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-10-04 10:37:58.347 INFO 14820 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
2018-10-04 10:37:58.478 INFO 14820 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-10-04 10:37:58.480 INFO 14820 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1985 ms
2018-10-04 10:37:58.653 INFO 14820 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-10-04 10:37:58.665 INFO 14820 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-10-04 10:37:58.666 INFO 14820 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-10-04 10:37:58.667 INFO 14820 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-10-04 10:37:58.667 INFO 14820 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-10-04 10:37:59.106 INFO 14820 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@443b7951: startup date [Thu Oct 04 10:37:56 CST 2018]; root of context hierarchy
2018-10-04 10:37:59.201 INFO 14820 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/index]}" onto public java.lang.String com.yiibai.demo.controller.WebController.index()
2018-10-04 10:37:59.205 INFO 14820 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-10-04 10:37:59.206 INFO 14820 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-10-04 10:37:59.245 INFO 14820 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-04 10:37:59.246 INFO 14820 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-04 10:37:59.296 INFO 14820 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-04 10:37:59.782 INFO 14820 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-10-04 10:37:59.992 INFO 14820 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-10-04 10:37:59.998 INFO 14820 --- [ main] com.yiibai.demo.DemoApplication : Started DemoApplication in 4.51 seconds (JVM running for 5.12)
現在,應用程式已在Tomcat埠8080上啟動。
現在開啟瀏覽器存取URL => http://localhost:8080/index
, 看到如下所示的輸出 -