Spring Boot Thymeleaf部署Tomcat后无法加载index.html报404错误
解决Spring Boot + Thymeleaf部署Tomcat出现404的问题
针对你部署后无法加载templates目录下index.html的问题,按以下步骤排查修复:
确保打包为WAR包
Spring Boot部署到外部Tomcat必须使用WAR格式,在pom.xml中修改打包方式并排除内置Tomcat:<packaging>war</packaging> <dependencies> <!-- 排除内置Tomcat,由外部Tomcat提供 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> </dependencies>修改启动类继承SpringBootServletInitializer
启动类需要适配外部Servlet容器,重写configure方法:@SpringBootApplication public class YourAppApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(YourAppApplication.class); } public static void main(String[] args) { SpringApplication.run(YourAppApplication.class, args); } }添加跳转控制器
Thymeleaf的templates目录下的页面无法直接访问,需要通过Controller映射根路径到index页面:@Controller public class IndexController { @GetMapping("/") public String index() { // 自动匹配templates/index.html,无需加.html后缀 return "index"; } }检查Thymeleaf依赖与配置
确保pom.xml中引入了Thymeleaf starter:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>同时确认
application.properties中Thymeleaf配置正确(默认配置可省略,如需自定义参考):spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.cache=false # 开发环境关闭缓存,避免页面修改不生效确认Tomcat部署访问路径
将打包好的WAR包放入Tomcat的webapps目录,启动Tomcat后:- 如果WAR包名为
ROOT.war,访问路径为http://localhost:8080/ - 如果WAR包名为
your-app.war,访问路径为http://localhost:8080/your-app/
- 如果WAR包名为
内容的提问来源于stack exchange,提问作者Amusement
相关产品推荐
相关产品推荐

