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](https://github.com/Controller "@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應用程序(Yiibai.com)</title>
   </head>
   <body>
      <h4>Thymeleaf Spring Boot web應用程序示例</h4>
      <p>
          Power by Yiibai.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[email protected]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[email protected]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, 看到如下所示的輸出 -

Spring Boot Thymeleaf示例