Thymeleaf无法检测spring-boot项目中的模板
我的Spring启动应用程序中具有以下项目结构,我想在其中使用Thymeleaf
I have the following project structure in my Spring boot app, in which I want to use Thymeleaf
projectName
-Gradle-Module1(Spring boot module)
-build
-src
-main
-resources
-templates
index.html
build.gradle
-Gradle-Module2
...
build.gradle
...
但是spring-boot找不到我的模板目录,并显示警告
but the spring-boot cannot find my template directory and is showing warning
Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
PS:我正在使用@EnableAutoConfiguration
在我的控制器代码中,我正在做类似的事情
In my controller code I am doing something like
@Controller
@EnableAutoConfiguration
public class BaseController {
@RequestMapping(value = "/")
public String index() {
return "index.html";
}
}
和index.html
文件仅显示世界.
因此通常它应该在src/resources/templates/
(我想是相同的Gradle模块)内部查看,但是以某种方式无法找到它.
so typically it should look inside src/resources/templates/
(of same Gradle module I suppose) , but somehow it is not able to find it.
当我尝试访问localhost:8080
时
我遇到错误Error resolving template "index.html", template might not exist or might not be accessible by any of the configured Template Resolvers
有什么我想念的吗?
when I try to access localhost:8080
I am getting below error Error resolving template "index.html", template might not exist or might not be accessible by any of the configured Template Resolvers
Is there anything I am missing?
任何指针都表示赞赏.
谢谢.
您必须按以下方式配置Thymeleaf:
You have to configure Thymeleaf as follows:
@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
类中.
Spring doc recommends to add @EnableAutoConfiguration
annotation to your primary @Configuration
class.
似乎您的项目结构也不正确,典型的软件包层次结构是:
Also it seems you have wrong project structure, the typical package hierarchy is:
src
|- main
|- java
|- resources
|- static
|- templates
|- test
在这种情况下,您的模板将位于src/main/resources/templates
中,而不位于src/resources/templates/
中.
In this case your templates will be in src/main/resources/templates
, not in src/resources/templates/
.