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

求助:Spring Boot无法返回templates目录下HTML文件的问题

Spring Boot无法返回templates目录下HTML文件的解决方案

核心问题原因

@RestController 是 @Controller + @ResponseBody 的组合注解,它会让控制器中所有方法的返回值直接作为HTTP响应体返回(也就是你看到的字符串"index"),不会触发视图解析器去匹配templates目录下的index.html文件——这才是问题的根源,和你添加的Thymeleaf配置无关。

具体解决办法

  • 直接替换注解:如果你的控制器主要用于返回HTML视图,把类上的@RestController换成@Controller,此时返回的"index"会被视图解析器识别,配合Thymeleaf配置找到/templates/index.html文件。
  • 若必须保留@RestController:在需要返回HTML的方法上,改用ModelAndView作为返回值,绕过@ResponseBody的默认处理,示例代码:
@GetMapping("/")
public ModelAndView index() {
    return new ModelAndView("index");
}

额外检查项

  • 确认项目已引入Thymeleaf starter依赖:
    Maven(pom.xml):
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Gradle(build.gradle):

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
  • 修正Thymeleaf配置(可选,Spring Boot默认已包含正确配置):
spring.thymeleaf.prefix=/templates/
spring.thymeleaf.suffix=.html

注意prefix末尾的斜杠,避免路径拼接时出现错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:50:14