SpringBoot Thymeleaf模板生成静态html
时间: 2024-09-13 18:18:24 浏览: 87
Spring Boot结合Thymeleaf是一个流行的前端模板引擎选择,用于简化Web应用的开发过程。Thymeleaf允许你使用HTML作为视图语言,并嵌入表达式和条件语句,它能动态地渲染数据。在Spring Boot项目中,Thymeleaf主要用于生成静态HTML页面。
步骤如下:
1. 添加依赖:在你的`pom.xml`文件中添加Thymeleaf的依赖,如:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 配置模板前缀和后缀:在`application.properties`或`application.yml`中配置模板的位置:
```properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
```
3. 创建视图:在指定目录创建HTML模板文件,例如`templates/home.html`,然后编写包含Thymeleaf标签的HTML内容。
4. 编写控制器:创建Controller,通过`@GetMapping`或其他注解映射URL到特定的视图,比如返回Thymeleaf模板:
```java
@GetMapping("/")
public String home() {
Model model = new Model();
// 设置模型属性,如model.addAttribute("message", "Hello World!");
return "home"; // 返回"home.html"模板
}
```
5. 渲染模板:当用户请求对应的URL时,Spring Boot会解析模板并将Model中的数据注入其中,生成并返回最终的静态HTML。
阅读全文
相关推荐


















