Tomcat Servlet: Error 404 - The requested resource is not available

Tom Haddad picture Tom Haddad · Oct 6, 2013 · Viewed 305.6k times · Source

I am completely new to writing a Java Servlet, and am struggling to get a simple HelloWorld example to work properly.

The HelloWorld.java class is:

package crunch;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
}

I am running Tomcat v7.0, and have already read similar questions, with responses referring to changing the invoker servlet-mapping section in web.xml, this section actually doesn't exist in mine, and when I added it the same problem still occurred.

Answer

user2511414 picture user2511414 · Oct 6, 2013

try this (if the Java EE V6)

package crunch;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet(name="hello",urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
}

now reach the servlet by http://127.0.0.1:8080/yourapp/hello

where 8080 is default tomcat port, and yourapp is the context name of your applciation