Tomcat 10下Java EE 8 Web应用URL映射问题:@WebServlet注解配置后访问出现404如何解决?
Hey there, let's break down why you're seeing that 404 error and how to fix it quickly. The main issue here is a package change between Java EE 8 and Jakarta EE (which Tomcat 10 uses)—here's what you need to do:
1. Understand the Root Cause
Tomcat 10 and above are built for Jakarta EE 9+, which replaced all javax.servlet packages with jakarta.servlet. Your current code uses Java EE 8's javax.servlet.annotation.WebServlet annotation, which Tomcat 10 doesn't recognize. That's why your Servlet isn't being mapped to the URL, leading to the 404.
2. Update Dependencies (If Using Build Tools)
If you're using Maven or Gradle, swap your old Java EE Servlet dependency for the Jakarta EE equivalent:
- For Maven, replace this in your
pom.xml:
With:<!-- Old Java EE 8 dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency><!-- Jakarta EE 9+ dependency for Tomcat 10 --> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>5.0.0</version> <scope>provided</scope> </dependency>
3. Fix Your Servlet's Import Statements
Update all javax.servlet imports in your HelloServlet.java to use jakarta.servlet instead. Here's the corrected code:
import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @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"); System.out.println("Get Requests"); PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("<h1>" + message + "</h1>"); out.println("</body></html>"); } public void destroy() { } }
4. Double-Check Your Access URL
Make sure you're using the correct full URL:
- If you deployed your app as
ROOT.war(so it's the default app on Tomcat), the URL should behttp://localhost:8080/hello-servlet(matches your current href). - If your app has a context path (e.g., deployed as
myapp.war), the URL needs to include that:http://localhost:8080/myapp/hello-servlet. To avoid hardcoding, use a relative link in yourindex.jsplike<a href="hello-servlet">Hello Servlet</a>instead of an absolute URL.
Quick Additional Checks
- Verify Tomcat 10 started without errors in its logs.
- Confirm your compiled
HelloServlet.classis present inWEB-INF/classesinside your deployed war file.
内容的提问来源于stack exchange,提问作者Prabhath Jay

