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

SpringBoot+Thymeleaf项目无法跳转index.html外页面问题求助

问题解决方案

根因定位

你的问题核心是Spring Boot启动类的包扫描范围不包含Controller所在包,导致HelloController没有被Spring容器识别加载,/hello接口不存在,访问时报404;同时你关闭了Spring Boot默认的白标错误页,又没有自定义error.html模板,所以报错时连带抛出找不到error模板的异常。

解决步骤

  • 第一步:调整包扫描配置,两种方案二选一即可
    • 方案1:打开启动类中被注释的@ComponentScan注解,修改为正确的扫描范围:
      @SpringBootApplication
      @ComponentScan(basePackages = "it.uniroma3.siw")
      public class ProgettoApplication {
          public static void main(String[] args) {
              SpringApplication.run(ProgettoApplication.class, args);
          }
      }
      
    • 方案2:调整启动类的位置,把启动类移到it.uniroma3.siw包下,Spring Boot默认会扫描启动类所在包及其所有子包,不需要额外配置@ComponentScan
  • 第二步:确认hello.html文件位置,检查是否放在src/main/resources/templates目录下,文件名大小写和Controller返回的字符串完全一致(Windows系统大小写不敏感,Linux系统大小写敏感,建议统一用小写避免兼容问题)
  • 第三步:如果不需要自定义错误页,可以把application.properties中的server.error.whitelabel.enabled=false改为true,恢复默认错误页,避免找不到error模板的次生报错;如果需要自定义错误页,在templates目录下新建error.html即可
  • 第四步:重启项目,验证/hello接口是否可以正常访问

额外排查点

如果调整后还是有问题,可逐一检查以下内容:

  • 检查HelloController上的注解是不是@Controller,不要错用@RestController(如果用RestController会直接把返回的字符串当成响应体,不会走视图解析器跳转模板)
  • 确认thymeleaf依赖是否正确导入,pom.xml中需包含:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  • 执行Maven clean install后,检查target/classes/templates目录下是否存在hello.html文件,避免资源没有被正确打包

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:15:04