Spring Thymeleaf无法解析模板

时间:2018-09-16 08:12:52

标签: java spring thymeleaf

我的问题是我无法显示Thymeleaf模板。我怀疑配置错误,但似乎找不到。在此先感谢:)

pom.xml:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>
...
<properties>
        ...
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.0.3</thymeleaf-layout-dialect.version>
    </properties>
...
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
        </dependency>

模板位于:src/main/resources/templates/home.html

Spring配置:

server.servlet.context-path=/mityo
server.port=8080
...
spring.thymeleaf.enabled=true
spring.thymeleaf.cache=false
spring.thymeleaf.check-template=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.mode=html5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=/resources/templates/

控制器:

@Controller
@RequestMapping("buy")
public class HomeController {

    public String buy(Model model) {
        return "home";
    }
}

我正在尝试访问:localhost:8080/mityo/buy并获得404。

另一件事,任何人都可以解释(或提供文档链接)哪个servlet用于“返回”模板html吗?是Spring调度程序servlet吗?


好的,所以我忘记了@GetMapping,谢谢@benjamin c。 但是添加它会产生:

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "home", template might not exist or might not be accessible by any of the configured Template Resolvers

3 个答案:

答案 0 :(得分:1)

@RequestMapping("/")函数之前放置buy

@RequestMapping("/")
public String buy(Model model) {
    return "home";
} 

如果您的课程中包含多个功能,springboot将不知道该请求将使用哪个功能。 SpringBoot使用Thymeleaf是模板的默认设置。您不需要为此配置。

答案 1 :(得分:1)

为避免404响应,请在@GetMapping方法中添加buy注释。

@GetMapping
public String buy(Model model) {
    return "home";
}

答案 2 :(得分:1)

请删除配置:spring.thymeleaf.prefix = / resources / templates / 默认情况下,此位置是Thymeleaf引擎使用的位置。

更新: 如果要更改默认位置(在资源目录下),可以使用: spring.thymeleaf.prefix = classpath:/ templates /