Spring boot中使用Thymeleaf
时间: 2024-08-14 22:07:31 浏览: 33
Spring Boot中使用Thymeleaf作为模板引擎,是为了将前端视图和后端Java应用程序分离,使得页面渲染更加快捷高效。以下是使用步骤:
1. 添加依赖:在你的`pom.xml`文件中添加Thymeleaf的starter依赖,例如:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 配置模板路径:在application.properties或application.yml中设置Thymeleaf的视图位置:
```properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
```
这里指定模板文件放在`templates`目录下,并以`.html`结尾。
3. 创建视图:在指定的路径下创建HTML文件,这些文件会被Thymeleaf解析并动态替换数据。例如,你可以有一个`home.html`文件,里面可以有如`#{message}`这样的表达式引用模型属性。
4. 定义模型和控制器:在Controller中,你需要返回一个包含数据的对象(通常是ModelAndView),并将数据注入到模型中:
```java
@GetMapping("/")
public String home(@ModelAttribute("model") Model model) {
model.addAttribute("message", "Hello from Thymeleaf");
return "home";
}
```
5. 渲染视图:当用户访问对应的URL时,Spring Boot会自动选择配置好的模板引擎来渲染页面。