我的Spring Boot应用程序中具有以下项目结构,我想在其中使用Thymeleaf
projectName -Gradle-Module1(Spring boot module) -build -src -main -resources -templates index.html build.gradle -Gradle-Module2 ... build.gradle ...
但spring-boot找不到我的模板目录,并显示警告
Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
PS:我正在使用 @EnableAutoConfiguration
@EnableAutoConfiguration
在我的控制器代码中,我正在做类似的事情
@Controller @EnableAutoConfiguration public class BaseController { @RequestMapping(value = "/") public String index() { return "index.html"; } }
和index.html文件只是打印你好世界。
index.html
因此通常它应该在src/resources/templates/(我认为是相同的Gradle模块)内部查找,但是以某种方式无法找到它。
src/resources/templates/
当我尝试访问时,localhost:8080 我得到以下错误信息Error resolving template "index.html", template might not exist or might not be accessible by any of the configured Template Resolvers 我缺少什么吗?
localhost:8080
Error resolving template "index.html", template might not exist or might not be accessible by any of the configured Template Resolvers
任何指针表示赞赏。
谢谢。
您必须按以下方式配置Thymeleaf:
@Configuration public class ThymeleafConfig { @Bean public SpringResourceTemplateResolver templateResolver() { SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setCacheable(false); templateResolver.setPrefix("classpath:/templates/"); templateResolver.setSuffix(".html"); return templateResolver; } @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine(); springTemplateEngine.addTemplateResolver(templateResolver()); return springTemplateEngine; } @Bean public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setOrder(1); return viewResolver; } }
Spring doc建议将@EnableAutoConfiguration注释添加到您的主@Configuration类。
@Configuration
似乎您的项目结构错误,典型的包层次结构为:
src |- main |- java |- resources |- static |- templates |- test
在这种情况下,您的模板将位于中src/main/resources/templates,而不是中src/resources/templates/。
src/main/resources/templates