springboot如何创建基于Thymeleaf模板引擎
时间: 2024-11-13 15:15:18 浏览: 37
在Spring Boot项目中集成Thymeleaf模板引擎,你可以按照以下步骤操作:
1. 添加依赖:首先在你的`pom.xml`文件中添加Thymeleaf和Spring Web相关的依赖。例如:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
```
2. 配置视图解析器:在`application.properties`或`application.yml`中配置视图的位置以及模板引擎名称:
```properties
spring thymeleaf mode=HTML5
spring.thymeleaf.prefix=/templates/
spring.thymeleaf.suffix=.html
```
这里设置前缀为`/templates/`,后缀为`.html`。
3. 创建模板文件:在`src/main/resources/templates`目录下创建你的HTML模板文件,比如`index.html`。
4. 配置Controller:在Controller类中返回Thymeleaf模型数据,并指定响应视图:
```java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "Hello from Thymeleaf!");
return "index"; // 指向你之前配置的模板文件名
}
}
```
5. 访问页面:通过访问`http://localhost:8080/`(假设你的应用运行在本地8080端口),Spring Boot会渲染Thymeleaf模板并显示内容。
阅读全文
相关推荐


















