Spring boot整合 Thymeleaf 模板
1. Thymeleaf模板引擎
Thymeleaf 是一种模板语言,它包含数据模型(Data)、模板(Template)、模板引擎(TemplateEngine)和结果文档( Result Documents )。
-
数据模型 数据是信息的表现形式和载体,可以是符号、文字、数字、语音、图像、视频等。数据和信息是不可分离的,数据是信息的表达,信息是数据的内涵。数据本身没有意义,数据只有对实体行为产生影响时才成为信息。 模板 模板,是一个蓝图,即一个与类型无关的类。编译器在使用模板时,会根据模板实参对模板进行实例化,得到一个与类型相关的类。 模板引擎 模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。 结果文档 一种特定格式的文档,比如用于网站的模板引擎就会生成一个标准的HTML文档。
Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。类似 JSP , Velocity , FreeMaker等, 它也可以轻易的与 Spring MVC 等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比, Thymeleaf 最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。
2. Spring boot 整合
2.1 工程创建
直接使用idea创建Spring boot 项目,可以直接选择需要的相关依赖,或者后期在pom文件中添加即可。
2.2 pom依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
</dependencies>
2.3 yml配置
主要是thymeleaf的相关配置,方便程序到指定路径下查找文件。
server:
port:
8085
spring:
application:
name: web
thymeleaf:
cache: false
suffix: .html
encoding: UTF-8
prefix: classpath:/templates/
2.4 接口
@Controller
public class IndexController {
@GetMapping("/index")
public String index() {
return "index";
}
}
2.5 访问测试
访问 http://localhost:8085/index
3. 总结
以上便是spring boot 整合thymeleaf的全部过程。
thymeleaf的相关使用可以参考官方文档。
https://www.thymeleaf.org/
