Tomcat Servlet: Error 404 - The requested resource is not available
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
You definitely need to map your servlet onto some URL. If you use Java EE 6 (that means at least Servlet API 3.0) then you can annotate your servlet like
@WebServlet(name="helloServlet", urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
//rest of the class
Then you can just go to the localhost:8080/yourApp/hello
and the value should be displayed. In case you can't use Servlet 3.0 API than you need to register this servlet into web.xml
file like
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>crunch.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
Writing Java servlets is easy if you use Java EE 7
@WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello World");
out.flush();
}
}
Since servlet 3.0
The good news is the deployment descriptor is no longer required!
Read the tutorial for Java Servlets.