1. 简介
Thymeleaf 是一个广泛用于 Spring Boot 项目的模板引擎,常用于动态生成 HTML 页面。Spring Boot 默认会从特定目录加载模板文件,但有时我们可能需要自定义模板路径,甚至使用多个模板目录。
本文将介绍如何修改默认模板目录,以及如何配置多个模板位置。适合有一定 Spring Boot 开发经验的开发者参考,避免踩坑。
2. 环境准备
在开始之前,确保你的项目中已经引入了 Thymeleaf 的依赖。如果使用 Maven 构建项目,需在 pom.xml
中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>3.1.5</version>
</dependency>
添加完成后,Spring Boot 会自动配置 Thymeleaf 的基本设置。
3. 修改默认模板目录
默认情况下,Spring Boot 会在 src/main/resources/templates
目录下查找模板文件。我们可以在这个目录下组织多个子目录,但有时候需要将模板文件集中到其他目录中,比如 templates-2
。
✅ 示例:将模板文件放在 templates-2
中
创建一个 HTML 模板文件,路径为 src/main/resources/templates-2/hello.html
,内容如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Enums in Thymeleaf</title>
</head>
<body>
<h2>Hello from 'templates/templates-2'</h2>
</body>
</html>
再创建一个简单的控制器,用于返回该模板:
@GetMapping("/hello")
public String sayHello() {
return "hello";
}
✅ 配置新目录
在 application.properties
中添加以下配置,告诉 Thymeleaf 使用新的模板目录:
spring.thymeleaf.prefix=classpath:/templates-2/
重启应用后,访问 /hello
接口即可看到页面内容。
4. 配置多个模板目录
如果我们希望同时使用多个模板目录,比如默认的 templates
和新增的 templates-2
,可以通过自定义 ClassLoaderTemplateResolver
Bean 实现。
✅ 自定义模板解析器
添加以下配置类:
@Configuration
public class ThymeleafConfig {
@Bean
public ClassLoaderTemplateResolver secondaryTemplateResolver() {
ClassLoaderTemplateResolver secondaryTemplateResolver = new ClassLoaderTemplateResolver();
secondaryTemplateResolver.setPrefix("templates-2/");
secondaryTemplateResolver.setSuffix(".html");
secondaryTemplateResolver.setTemplateMode("HTML");
secondaryTemplateResolver.setCharacterEncoding("UTF-8");
secondaryTemplateResolver.setOrder(1);
secondaryTemplateResolver.setCheckExistence(true);
return secondaryTemplateResolver;
}
}
这样,Thymeleaf 会先尝试从默认目录加载模板,如果找不到,会去 templates-2
目录查找。
5. 常见错误及解决方案
在使用 Thymeleaf 时,经常会遇到模板找不到的问题,错误信息如下:
Error resolving template [hello], template might not exist or might not be accessible by any of the configured Template Resolvers
以下是几种常见原因及解决办法:
5.1. 控制器中模板名拼写错误
模板文件名与控制器返回的字符串必须完全一致(不包括扩展名)。例如,如果模板文件是 hello.html
,控制器中应返回 "hello"
。
⚠️ 注意大小写问题:Windows 系统不区分大小写,而 Linux 系统是区分的。本地测试没问题,部署后报错,可能就是这个问题。
5.2. 控制器中返回了扩展名
Thymeleaf 会自动加上 .html
后缀,因此在控制器中返回模板名时不要带扩展名。
❌ 错误写法:
return "hello.html";
✅ 正确写法:
return "hello";
5.3. 模板未放在正确目录
如果你没有使用默认目录,又没有配置 spring.thymeleaf.prefix
或自定义的 ClassLoaderTemplateResolver
,Thymeleaf 就无法找到模板。
确保你配置了正确的路径,或者添加了多个模板解析器。
6. 小结
本文介绍了如何在 Spring Boot 中修改 Thymeleaf 的模板目录,包括:
- 修改默认模板目录(通过配置
spring.thymeleaf.prefix
) - 配置多个模板目录(通过自定义
ClassLoaderTemplateResolver
Bean) - 常见错误及排查方法
这些配置在实际开发中非常实用,尤其在项目结构复杂、模板需要分组管理时尤为重要。合理配置可以提升项目的可维护性和灵活性。
完整示例代码可在 GitHub 获取。