我正在用Thymeleaf运行Spring Boot应用程序。当我通过IDE(IntelliJ)运行应用程序时,一切运行正常。但是,当我通过命令行(java -jar)运行应用程序时,视图无法解析,并且出现以下错误:
java -jar
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:245) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011) at org.thymeleaf.spring3.view.ThymeleafView.renderFragment(ThymeleafView.java:335) at org.thymeleaf.spring3.view.ThymeleafView.render(ThymeleafView.java:190) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1225) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1012) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
这是我的设置:
我的目录结构
PROJECT-ROOT --src --main --java --controllers --[CLASS WITH MAIN METHOD] --views --index.html
我的模板解析器:
@Bean public ViewResolver viewResolver() { ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setTemplateMode("XHTML"); templateResolver.setPrefix("views/"); templateResolver.setSuffix(".html"); SpringTemplateEngine engine = new SpringTemplateEngine(); engine.setTemplateResolver(templateResolver); ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(engine); return viewResolver; }
我应该将视图放在哪里,以便从jar文件运行时可以正确解析它们?
我认为答案是,这取决于您的构建配置。目录“ src / main / views”不是任何常用构建工具的标准资源位置,因此您必须将其显式添加到用于构建jar的工具的配置中。
如果我是你,我会顺其自然(为什么会有所不同?),只对类路径资源使用“ src / main / resources”。我还将完全省略thymeleaf配置,并让Spring Boot处理它,将模板放在“ src / main / resources / templates”中。