mvc怎么使用thymeleaf
时间: 2025-01-29 07:15:00 浏览: 27
Thymeleaf是一个现代化的服务器端Java模板引擎,适用于Web和独立环境。它的主要目标是为开发工作流程带来优雅的自然模板——可以在浏览器中正确显示,并且可以作为静态原型,让前端团队可以独立于后端团队工作。
在Spring MVC中使用Thymeleaf的步骤如下:
1. **添加依赖**:
在你的`pom.xml`文件中添加Thymeleaf的依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. **配置视图解析器**:
Spring Boot会自动配置Thymeleaf的视图解析器,你不需要手动配置。但如果你需要自定义配置,可以在`application.properties`或`application.yml`中进行配置。
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="${message}">Hello, World!</h1>
</body>
</html>
```
4. **创建控制器**:
在你的Spring MVC控制器中,返回视图名称:
```java
@Controller
public class MyController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "index";
}
}
```
5. **运行应用程序**:
启动Spring Boot应用程序,访问`http://localhost:8080/`,你应该会看到页面显示“Hello, Thymeleaf!”。
通过以上步骤,你就可以在Spring MVC中使用Thymeleaf来渲染动态页面了。
阅读全文
相关推荐



















