搭建springboot项目thymeleaf模板
时间: 2024-09-23 18:07:45 浏览: 78
搭建Spring Boot项目并集成Thymeleaf模板可以分为以下几个步骤:
1. **创建Spring Boot项目**:
使用Spring Initializr(https://start.spring.io/)在线创建一个新的Spring Boot项目,选择Web、Thymeleaf依赖项以及需要的其他基础库。
2. **添加依赖**:
将Thymeleaf作为Maven或Gradle项目的依赖添加到pom.xml或build.gradle文件中。例如,在Maven中,添加以下内容:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
3. **配置Thymeleaf**:
- 配置`application.properties`或`application.yml`,指定视图解析器。默认路径通常是`classpath:/templates/`:
```properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
```
- 如果需要,也可以设置HTML5模式:
```properties
spring.thymeleaf.mode=HTML5
```
4. **创建模板文件**:
在指定的目录(如`src/main/resources/templates`)下创建HTML文件,并使用Thymeleaf标签,比如`<th:block>`、`<th:if>`等。
5. **编写控制器和视图映射**:
创建Controller类,定义处理HTTP请求的方法。在返回值里,你可以使用`ModelAndView`来关联数据和模板,示例:
```java
@GetMapping("/")
public String home(@ModelAttribute("model") Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "home"; // 这里的"home"就是对应的Thymeleaf模板名称
}
```
6. **运行应用**:
启动Spring Boot应用,然后通过浏览器访问`http://localhost:8080/` (假设端口为8080),你应该能看到Thymeleaf渲染后的页面。
阅读全文
相关推荐


















