Java Thymeleaf无法检测到spring启动项目中的模板
在我的Spring boot应用程序中有以下项目结构,我想在其中使用ThymeleafJava Thymeleaf无法检测到spring启动项目中的模板,java,spring,spring-boot,thymeleaf,Java,Spring,Spring Boot,Thymeleaf,在我的Spring boot应用程序中有以下项目结构,我想在其中使用Thymeleaf projectName -Gradle-Module1(Spring boot module) -build -src -main -resources -templates index.html build.gradle -G
projectName
-Gradle-Module1(Spring boot module)
-build
-src
-main
-resources
-templates
index.html
build.gradle
-Gradle-Module2
...
build.gradle
...
但是spring引导找不到我的模板目录,并显示警告
找不到模板位置:classpath:/templates/(请添加一些模板或检查您的Thymeleaf配置)
PS:我正在使用@EnableAutoConfiguration
在我的控制器代码中,我正在执行以下操作:
@Controller
@EnableAutoConfiguration
public class BaseController {
@RequestMapping(value = "/")
public String index() {
return "index.html";
}
}
而index.html
文件只打印hello world
因此,通常它应该查看src/resources/templates/
(我想是同一个Gradle模块),但不知何故它无法找到它
当我尝试访问localhost:8080
时,我发现以下错误
解析模板“index.html”时出错,模板可能不存在或任何已配置的模板解析程序都无法访问该模板`
我有什么遗漏吗?欢迎指点。谢谢。您应该只返回文件名。例如,没有.hmtl
@RequestMapping(value = "/")
public String index() {
return "index";
}
您必须按如下方式配置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;
}
}
将@EnableAutoConfiguration
注释添加到主@Configuration
类
此外,您似乎有错误的项目结构,典型的包层次结构是:
src
|- main
|- java
|- resources
|- static
|- templates
|- test
在这种情况下,您的模板将位于
src/main/resources/templates
,而不是src/resources/templates/
中。您尝试了该操作,但面临问题2017年3月22日星期三15:33:08 IST出现意外错误(类型=内部服务器错误,状态=500)。解析模板“index”时出错,模板可能不存在,或者任何已配置的模板解析程序都可能无法访问该模板
请为requestmapping和index.html文件发布您的类,以便我们获得更多上下文。您是否正在使用任何形式的身份验证?能否为您的questmappin和index.html文件发布类?如果你有更大的stacktrace,那会很有帮助。你只是用return“index”修改了你的帖子
我已经添加了控制器类,目前我正在尝试学习React+Spring引导,所以没有太多的代码,而且我的index.html只包含像Hello World这样的打印语句。这是一个很好的问题。谢谢你的邀请!非常感谢。行“templateResolver.setPrefix(“classpath:/templates/””);为我修复了使用jar打包运行Spring Boot时的问题。这解决了我的问题。我已经用Intellij IDEA开发了,我不知何故能够在没有这种配置的情况下运行thymeleaf。当我将项目打包到JAR并在服务器上运行它时,我们注意到了这个问题。花了很多时间终于找到了这个。
src
|- main
|- java
|- resources
|- static
|- templates
|- test