thymeleaf调用java
时间: 2023-05-29 18:04:10 浏览: 86
Thymeleaf 是一个基于 Java 的模板引擎,因此可以轻松地在 Java 中调用 Thymeleaf。
以下是 Thymeleaf 在 Java 中的基本用法:
1. 首先,需要在项目中添加 Thymeleaf 的依赖项,例如:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 在 Java 代码中,使用 Thymeleaf 的 TemplateEngine 类来创建一个模板引擎对象:
```
TemplateEngine templateEngine = new TemplateEngine();
```
3. 然后,可以使用 TemplateEngine 对象的 process 方法来处理模板,例如:
```
Context context = new Context();
context.setVariable("name", "Thymeleaf");
String html = templateEngine.process("template.html", context);
```
在上面的例子中,我们创建了一个 Context 对象,并将变量 name 设置为 "Thymeleaf"。然后,我们调用了 TemplateEngine 对象的 process 方法,将模板文件 "template.html" 和 Context 对象作为参数传递给该方法。最终,process 方法将返回一个 HTML 字符串,其中的变量将被替换为其对应的值。
除了上述基本用法外,Thymeleaf 还提供了很多其他功能,例如条件语句、循环语句、表单绑定等等。要学习更多有关 Thymeleaf 的详细信息,请参考官方文档。