如何从春季启动中找到Thymeleaf模板

Gus*_*tav 3 java spring maven thymeleaf spring-boot

我正在尝试按照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>
Run Code Online (Sandbox Code Playgroud)

在控制器中我有

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

在视图中:

<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>   
Run Code Online (Sandbox Code Playgroud)

Cha*_*ndu 9

Spring Boot包含对百万美元模板引擎的自动配置支持,您的模板将自动从src/main/resources/templates中获取.

如果您自定义模板位置,请使用Spring Boot中提供的thymeleaf属性配置.

  • spring.thymeleaf.check-template = true#在呈现模板之前检查模板是否存在.

  • spring.thymeleaf.check-template-location = true#检查模板位置是否存在.

  • spring.thymeleaf.enabled = true#启用MVC Thymeleaf视图分辨率.

  • spring.thymeleaf.prefix = classpath:/ templates /#在构建URL时添加前缀以查看名称的前缀.

  • spring.thymeleaf.suffix = .html#在构建URL时附加到视图名称的后缀.


cho*_*way 6

thymeleaf 模板的默认目录位置是:

src/main/resources/templates
Run Code Online (Sandbox Code Playgroud)

其他路径是 Spring Boot 的标准约定。

Spring Boot thymeleaf 目录结构


Him*_*waj 5

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