You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot项目模板访问异常:解析users模板失败

Spring Boot 模板解析500错误:无法找到"users"模板的解决方案

问题概述

Spring Boot项目中,UserController的根路径(/)@GetMapping方法返回名为"users"的模板,并向模型添加用户列表数据,但templates文件夹中仅存在index.html文件。访问根路径触发500内部服务器错误,提示无法解析模板[users];修改返回"index"模板则页面正常加载。

直接解决方案

方案1:重命名模板文件

将src/main/resources/templates/目录下的index.html重命名为users.html,让控制器返回的模板名称与实际文件完全匹配。

方案2:修改控制器返回值

如果希望保留index.html文件名,直接修改UserController中的返回值为"index",后续可在index.html中补充Thymeleaf数据绑定逻辑:

@GetMapping("/")
public String AllUsers(Model model) {
    model.addAttribute("listUsers", userService.getAllUsers());
    return "index"; // 将返回值改为index
}

错误原因分析

Spring Boot集成Thymeleaf时,默认遵循以下模板解析规则:

  • 模板文件默认存放路径:src/main/resources/templates/
  • 文件名匹配规则:控制器返回的字符串 + 固定后缀.html。即返回"users"时,解析器会自动查找templates/users.html。
    由于你的项目中不存在users.html,仅存在index.html,因此返回"users"时触发模板未找到的500错误。

额外排查步骤(若上述方案无效)

  • 检查文件路径与大小写:确认模板文件是否在正确的templates目录下,Linux/Mac系统需注意文件名大小写敏感。
  • 确认Thymeleaf依赖:检查项目依赖中是否包含Thymeleaf starter(Maven示例):
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  • 检查模板配置:若自定义了Thymeleaf配置,验证application.properties/application.yml中的基础配置是否正确:
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.suffix=.html
    

内容的提问来源于stack exchange,提问作者negbi2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 04:45:19