如何从 spring boot 定位 Thymeleaf 模板

新手上路,请多包涵

我正在尝试按照 http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html 上的本教程学习如何向 Thymeleaf 模板发送响应。但我收到此错误:找不到模板位置:classpath:/templates/(请添加一些模板或检查您的 Thymeleaf 配置)

我将 message.html 文件放在 Other Sources 目录和 src/main/resources 下的 <default package> 下。

所以结构看起来像:

SomeProject -Other Sources –src/main/resources — <default package> —-message.html

我想知道为什么它显示在 <default package> 而不是 <template> 下?这可能是问题所在吗?如果是这样我应该如何改变它?我正在使用 netbeans 和 maven。有什么想法吗?这些是我在 pom.xml 中的依赖项:

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>

在我的控制器中

@RequestMapping(value = "message", method = RequestMethod.GET)
    public String messages(Model model) {
    model.addAttribute("messages", messageRepository.findAll());
    return "message";
}

在视图中:

 <ul th:each="message : ${messages}">
    <li th:text="${message.id}">1</li>
    <li><a href="#" th:text="${message.title}">Title ...</a></li>
    <li th:text="${message.text}">Text ...</li>
</ul>

原文由 Gustav 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 604
2 个回答

这里有 2 件事:1. 如果您使用的是 Maven,我假设没有对文件夹名称进行自定义。那么文件夹名称应该是 src 而不是 source。 2. 重命名文件夹后,将模板移动到 src/resources 内的“templates”文件夹中,这应该可以正常运行。

原文由 Himanshu Bhardwaj 发布,翻译遵循 CC BY-SA 3.0 许可协议

Spring Boot 包括对 thymeleaf 模板引擎的自动配置支持,您的模板将自动从 src/main/resources/templates 中获取。

如果您要自定义模板位置,请使用 Spring Boot 中可用的以下 thymeleaf 属性配置。

  spring.thymeleaf.check-template=true # Check that the template exists before rendering it.

 spring.thymeleaf.check-template-location=true # Check that the templates location exists.

 spring.thymeleaf.enabled=true # Enable MVC Thymeleaf view resolution.

 spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.

 spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.

原文由 Chandra 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题