Spring Boot Thymeleaf示例

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类文件以将Request URI重定向到HTML文件 -

package com.zyiz.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应用程序(zyiz.net)</title>
   </head>
   <body>
      <h4>Thymeleaf Spring Boot web应用程序示例</h4>
      <p>
          Power by zyiz.net
      </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.zyiz.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.zyiz</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.zyiz'
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.zyiz.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.zyiz.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.zyiz.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.zyiz.demo.DemoApplication          : Started DemoApplication in 4.51 seconds (JVM running for 5.12)

现在,应用程序已在Tomcat端口8080上启动。

现在打开浏览器访问URL => http://localhost:8080/index, 看到如下所示的输出 -