springboot中themyleaf
时间: 2023-07-03 19:22:46 浏览: 73
Thymeleaf 是一款流行的模板引擎,可以在 Spring Boot 中使用 Thymeleaf 实现动态页面渲染。以下是使用 Thymeleaf 的步骤:
1. 在 pom.xml 文件中添加 Thymeleaf 依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 在 application.properties 文件中配置 Thymeleaf 相关属性:
```properties
# Thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
```
3. 在 src/main/resources/templates 目录下创建 HTML 模板文件,使用 Thymeleaf 语法进行页面渲染。
4. 在 Controller 中使用 `@RequestMapping` 注解处理请求,并返回模板名称,例如:
```java
@Controller
public class HomeController {
@RequestMapping("/")
public String home(Model model) {
model.addAttribute("message", "Hello Thymeleaf!");
return "home";
}
}
```
在上述例子中,home() 方法返回模板名称 "home",Thymeleaf 会自动查找 "home.html" 文件进行页面渲染,同时将 "Hello Thymeleaf!" 传递给模板的 message 变量。
5. 在 HTML 模板文件中使用 Thymeleaf 语法进行页面渲染,例如:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf Example</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
```
在上述例子中,使用 `th:text` 属性将 message 变量的值显示在 h1 标签内。
以上是使用 Thymeleaf 进行动态页面渲染的基本步骤。Thymeleaf 还支持循环、条件判断、表单处理等复杂的页面渲染操作,具体语法可以参考 Thymeleaf 官方文档。