Spring Boot构建的RESTful服务部署Tomcat后出现404错误
部署Spring Boot RESTful服务到EC2的Tomcat后出现404错误
将基于Spring Boot/Maven的RESTful服务部署到运行在Amazon EC2 Linux实例上的Tomcat 10.1.9后,请求返回404错误(页面显示Not Found),但在Eclipse中启动服务并通过Postman访问时一切正常。
我怀疑是否在pom.xml中缺少某种Servlet映射(当前无web.xml文件),以下是pom.xml片段:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.11</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>ca.allauto</groupId> <artifactId>ups</artifactId> <version>v1</version> <name>ups</name> <description>RESTful service for UPS application</description> <packaging>war</packaging> <properties> <java.version>17</java.version> </properties> etc...
war包名称为ups-v1,我使用的访问URL为:http://[Public EC2 IPv4 address]:8080/ups-v1/api/ups
控制器中的RequestMapping配置如下:
@RestController @RequestMapping("/api") public class UpsController { @Autowired UpsService upsService; @GetMapping(value="/ups") public List<Ups> readUps() { return upsService.getUps(); } // etc...
请问我是否需要添加web.xml文件?
不需要额外添加web.xml文件,问题核心是版本兼容性
Tomcat 10基于Servlet 5.0,而你使用的Spring Boot 2.7.11仅支持到Servlet 4.0(对应Tomcat 9)。Servlet 5.0将原有javax.servlet包名改为jakarta.servlet,导致Spring Boot 2.x的war包无法在Tomcat 10中正常加载,这就是404错误的根源。
两种解决方案:
- 降级Tomcat:把EC2上的Tomcat换成9.x版本,直接匹配Spring Boot 2.7.x的Servlet版本支持,操作简单见效快。
- 升级Spring Boot:若要保留Tomcat 10,需将Spring Boot升级到3.x版本(3.x开始支持Jakarta EE 9+,适配Servlet 5.0+),你的项目已经使用Java 17,满足Spring Boot 3.x的版本要求。
额外验证步骤:
- 确认Tomcat的
webapps目录下已正确部署ups-v1.war,且Tomcat启动日志(Tomcat_HOME/logs/catalina.out)中无报错信息。 - 访问Tomcat管理页面
http://[EC2地址]:8080/manager/html,确认ups-v1应用状态为“running”。
内容的提问来源于stack exchange,提问作者Rob Gravelle
相关产品推荐
相关产品推荐

