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

使用IDEA部署Web应用到Tomcat 9.0.41时Servlet路径出现404错误的问题求助

404 Error with HelloServlet in Tomcat 9 & IDEA: Here's What's Wrong

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.java into WEB-INF/classes in the deployed project (you can find this in Tomcat's webapps folder or IDEA's deployment output directory).
  • Take a look at Tomcat's localhost.log file (in the logs folder) — it might show a "class not found" error for the jakarta.servlet classes, which confirms the package mismatch.

内容的提问来源于stack exchange,提问作者xuan xue

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 05:27:34