thymeleaf怎么用
时间: 2023-09-20 10:09:31 浏览: 48
Thymeleaf是一种模板引擎,用于在Web应用程序中生成动态HTML。以下是使用Thymeleaf的步骤:
1. 在pom.xml中添加Thymeleaf依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 在Spring Boot中配置Thymeleaf模板引擎:
```java
@Configuration
public class ThymeleafConfig {
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
}
```
3. 在HTML文件中使用Thymeleaf标记:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf Example</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
```
4. 在控制器中设置模型数据:
```java
@Controller
public class ExampleController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "index";
}
}
```
这样,当访问根路径时,将会渲染名为“index”的Thymeleaf模板,并将message属性的值设置为“Hello, Thymeleaf!”。
阅读全文