springboot整合thyme
时间: 2024-01-07 14:05:40 浏览: 19
Thymeleaf 是一种用于 Web 和独立环境的现代化服务器端 Java 模板引擎,能够处理 HTML、XML、JavaScript、CSS 和文本等各种类型的模板。
Spring Boot 提供了对 Thymeleaf 的自动化配置,可以非常方便地将 Thymeleaf 集成到你的应用程序中。
下面是整合步骤:
1.在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2.在 application.properties 文件中添加以下配置:
```properties
# 模板文件的位置,默认为classpath:/templates/
spring.thymeleaf.prefix=classpath:/templates/
# 后缀,默认为.html
spring.thymeleaf.suffix=.html
# 模板文件的编码,默认为UTF-8
spring.thymeleaf.encoding=UTF-8
# 开启模板缓存,默认为true
spring.thymeleaf.cache=true
```
3.在 src/main/resources/templates 目录下创建 HTML 模板文件,例如 index.html,添加以下内容:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Example</title>
</head>
<body>
<h1 th:text="${title}"></h1>
<p th:text="${message}"></p>
</body>
</html>
```
4.在 src/main/java 目录下创建控制器类,例如 IndexController.java,添加以下内容:
```java
@Controller
public class IndexController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("title", "Hello Thymeleaf");
model.addAttribute("message", "This is an example of Thymeleaf.");
return "index";
}
}
```
5.运行应用程序,在浏览器中访问 http://localhost:8080/ 即可看到页面内容。
以上就是 Spring Boot 整合 Thymeleaf 的基本步骤。你可以根据实际需求进行更多高级配置和功能实现。