使用IDEA部署Web应用到Tomcat 9.0.41时Servlet路径出现404错误的问题求助
Hey there! Let's figure out why your HelloServlet is throwing a 404 even though your index.jsp loads fine. The root cause here is a package mismatch between your code and Tomcat's supported API version.
The Core Issue
Tomcat 9.0.x is built to support the traditional Java EE Servlet API (using the javax.servlet package), but your code uses the newer jakarta.servlet package. This switch from javax to jakarta happened starting with Jakarta EE 9, which is only supported by Tomcat 10 and above. Since Tomcat 9 doesn't recognize the jakarta.servlet annotations/classes, it can't map your /hello-servlet endpoint, hence the 404.
Fix Options
You have two straightforward ways to resolve this:
Option 1: Adjust Your Code to Match Tomcat 9
Update all your import statements to use the javax.servlet package instead of jakarta.servlet:
import java.io.*; import javax.servlet.http.*; import javax.servlet.annotation.*; @WebServlet(name = "helloServlet", value = "/hello-servlet") public class HelloServlet extends HttpServlet { private String message; public void init() { message = "Hello World!"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("<h1>" + message + "</h1>"); out.println("</body></html>"); } public void destroy() { } }
After making this change, rebuild your project in IDEA and redeploy to Tomcat. The servlet should now be recognized.
Option 2: Upgrade Tomcat to Support Jakarta API
If you want to keep using the jakarta.servlet package (maybe you're learning the latest specs), upgrade your Tomcat installation to version 10.0.x or higher. These versions are compatible with Jakarta EE 9+, so your existing code will work without changes.
Quick Additional Checks
Just to be thorough, verify these points too:
- In IDEA's Project Structure > Modules > Dependencies, make sure the Servlet API dependency is pulled from your Tomcat 9 installation (not a standalone Jakarta EE library).
- Check that IDEA is compiling your
HelloServlet.javaintoWEB-INF/classesin the deployed project (you can find this in Tomcat'swebappsfolder or IDEA's deployment output directory). - Take a look at Tomcat's
localhost.logfile (in thelogsfolder) — it might show a "class not found" error for thejakarta.servletclasses, which confirms the package mismatch.
内容的提问来源于stack exchange,提问作者xuan xue

