一、为什么使用Thymeleaf
Thymeleaf是SpringBoot推荐使用的前端模板引擎。
Thymeleaf官方给出的定义是:
Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.
The main goal of Thymeleaf is to provide an elegant and highly-maintainable way of creating templates. To achieve this, it builds on the concept of Natural Templates to inject its logic into template files in a way that doesn’t affect the template from being used as a design prototype. This improves communication of design and bridges the gap between design and development teams.
Thymeleaf has also been designed from the beginning with Web Standards in mind – especially HTML5 – allowing you to create fully validating templates if that is a need for you.
二、Spring Boot 整合 Thymeleaf
1、在pom.xml文件引入thymeleaf
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- SpringBoot整合thymeleaf模板 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- SpringBoot整合thymeleaf模板 --> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.1.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
2、添加index.html
Thymeleaf有一个默认配置,配置信息放在了 org.springframework.boot.autoconfigure.thymeleaf 下的 ThymeleafProperties类中,具体如下:
所以Thymeleaf会默认在 "classpath:/templates/" 寻找html的文件,所以我们首先在resources下添加文件夹templates,再在templates文件夹下新建index.html文件,代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> ----------------------------------------------------------------------<br/> 这是Index.html页面<br/> ----------------------------------------------------------------------<br/> </body> </html>
3、添加Java类:IndexController
截图如下:
代码如下:
package com.demo.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping(value = {"","/","/index"}) //多个路由匹配 //@RequestMapping("/index") //单个路由匹配 public String Index(){ return "index"; } }
三、运行
打开浏览器,输入网址:http://localhost:8080/
四、总结
这应该算是最简单的Spring Boot 集成 Thymeleaf的方案!下一章将介绍一些Thymeleaf的基础用法!