0

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

SpiderGwen
  • 53
  • 1
  • 1
  • 7
  • You don't need to add `servlet-api.jar` to the Build Path, targeting the server runtime gives you those packages. What URL are you requesting that fails, and what server context (path) is your application, as a whole, set to deploy under? – nitind May 07 '20 at 00:36
  • @nitind Regarding the build path, I manually removed the entire tomcat package and added only the servlet-api.jar, just to be consistent with the tutorial I'm following. Even if I don't do this, I also get 404, which disappears after I export the project to a WAR. URL requested: http://localhost:8080/MyHelloServlet5/HelloWorld5 ContextPath: MyHelloServlet5 – SpiderGwen May 07 '20 at 23:44
  • Problem is solved when I build the project properly!!! – SpiderGwen May 09 '20 at 21:50

0 Answers0