【问题标题】:How to configure Thymeleaf template location如何配置 Thymeleaf 模板位置
【发布时间】:2019-06-14 21:22:04
【问题描述】:

我想在基于 Spring Boot 2.1.5 的应用程序中使用 Thymeleaf。但我不需要它来为RestController 创建 html 输出。而不是我希望它创建应用程序可以存储在磁盘上的 html 文件。

因此,我创建了两个 bean templateResolvertemplateEngine,就像 docs 描述的那样。模板存储在与RestController 相同的位置:src/main/resources/templates。比如一个叫index.html

但无论我配置哪个路径(有或没有classpath),我都会收到相同的错误消息:

    templateResolver.setApplicationContext(this.applicationContext);
    templateResolver.setPrefix("classpath:/resources/templates/");
    templateResolver.setSuffix(".html");

java.io.FileNotFoundException:类路径资源 [resources/templates/index.html] 无法打开,因为它没有 存在

我需要如何配置路径以使其工作 a) 在 STS 内和 b) 在创建的 jar 内?

解决此问题的另一种方法是改用spring-boot-starter-thymeleaf 并“抓取”其生成的输出,而不是通过嵌入式 Tomcat 公开它,但我不知道如何让它工作:

@GetMapping("/noneedforthis")
public String getIndexFileContent(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
    model.addAttribute("name", name);
    return "index";
}

【问题讨论】:

  • 我不明白你的问题。你想达到什么目的?提供静态 HTML 页面?
  • 不,我想创建基于多个模板的动态页面。但结果应该直接放入文件中,而不是通过网络服务器传递。我需要将这些文件存储在档案中并保存几年。
  • 没问题。只需阅读文档:thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
  • 我阅读了 Spring 特定的 Thymeleaf 文档,但留下了提到的问题

标签: java spring spring-boot thymeleaf


【解决方案1】:

我检查了我的 Eclipse 工作区的本地 target 目录和通过运行 maven install 创建的 jar:模板存储在 templates 中,而不是 resources/templates

在我的代码中缩短路径有所帮助,现在 Thymeleaf 可以找到模板。

为 Thymeleaf 使用 Spring Boot Starter 仍然是一个有趣的替代方案,但到目前为止我还没有找到方法。

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 1970-01-01
    • 2017-07-30
    • 2018-02-18
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多