I'm following a course and trying to create a servlet using Eclipse.
I have tried the following scenarios:
- JRE: 8, 10, 11
- Dynamic web module version: 3, 4
- Target runtime: Apache Tomcat v9.0
What Happened
In each combination of the above scenarios, these are the steps I completed: right click to create new dynamic web project --> right click to create a servlet inside a package (not the default package) --> add response.getWriter().println("<h1>Hello </h1>");
inside the doGet method --> add servlet-api.jar to build path --> Restart the server --> Run the servlet class on the server
In all scenarios, I get a 404 error as below:
Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists
In all scenarios, after I accidentally export the project into a WAR file, the error is gone and the servlet works.
I'm trying to create new projects to test my hypothesis and the same situation continues.
Here's the complete servlet code in one of the scenarios:
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/HelloWorld5")
public class HelloWorld5 extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorld5() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().println("<h1>Hello 5</h1>");
}
}
I have checked the following question and it's not answering my question
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Question
Please help me understand why all my projects are not working before and will work after exporting them into WAR files.
Updates based on comments:
URL requested: http://localhost:8080/MyHelloServlet5/HelloWorld5
ContextPath: enter image description here