Spring Boot配置Thymeleaf(gradle)的简单使用
Spring Boot是目前最为流行的Java Web框架之一,并被广泛应用于企业级软件开发。而Thymeleaf,则是一种支持HTML5/XHTML/XML的模板引擎,具有丰富的特性,能够满足开发者日常开发需求。
本文将介绍如何在Spring Boot中配置和使用Thymeleaf模板引擎,步骤如下:
一、添加依赖
Thymeleaf在Gradle项目中需要添加如下依赖:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}
二、配置模板引擎
在application.properties文件中添加如下配置:
spring.thymeleaf.cache=false spring.thymeleaf.enable-spring-el-compiler=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.mode=HTML5
配置说明:
- cache:是否启用缓存,默认为true,开发时建议关闭。
- enable-spring-el-compiler:是否启用Spring EL编译器,默认为false,开发时建议启用。
- prefix:模板文件存放路径,这里设置为classpath:/templates/,表示模板文件存放在项目代码的/templates目录下。
- suffix:模板文件后缀名,这里设置为.html。
- encoding:模板文件编码。
- mode:模板引擎模式,默认为HTML5。
三、创建模板文件
在项目的templates目录下,创建一个名为index.html的文件,内容如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf Test</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
四、创建控制器
在项目中创建一个控制器TestController,代码如下:
@Controller
public class TestController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("name", "world");
return "index";
}
}
这里定义了一个index方法,用来显示index.html模板,并向模板中添加一个name变量,值为world。
五、运行测试
启动项目并访问http://localhost:8080,应该会显示Hello, world!。
这里我们将name变量的值设置为了world,如果想要修改,只需要在TestController中修改即可,Thymeleaf会重新渲染模板。
总结
本文介绍了在Gradle项目中配置和使用Thymeleaf模板引擎的方法,通过示例代码,演示了如何创建模板文件、添加控制器并运行测试。虽然这只是个简单的例子,但理解了这个过程,开发者就可以轻松上手Thymeleaf,满足日常开发需求。
