i’m attempting to use apache tomcat 7.0 tomcat7 to access java servlets.
I have created a folder to hold all my webapp files under the ROOT folder in webapps.
The file structure is like this.
- Tomcat 7.0/webapps/myWebApp
- HelloHome.html
- WEB-INF
- web.xml
- classes
- com
- training
- HelloServlet.java
- HelloServlet.class
- training
- com
to call the servlet this web.xml code was used:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- To save as "hello\WEB-INF\web.xml" -->
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.training.HelloServlet</servlet-class>
</servlet>
<!-- Note: All <servlet> elements MUST be grouped together and
placed IN FRONT of the <servlet-mapping> elements -->
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>
the actual java code (compiled to generate a class file under the classes folder):
//To save as "<TOMCAT_HOME>\webapps\hello\WEB-INF\classes\HelloServlet.java"
package com.training;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Set the response MIME type of the response message
response.setContentType("text/html");
// Allocate a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
// Write the response message, in an HTML page
try {
out.println("<html>");
out.println("<head><title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
// Echo client's request information
out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
out.println("<p>Protocol: " + request.getProtocol() + "</p>");
out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
// Generate a random number upon each request
out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
out.println("</body></html>");
} finally {
out.close(); // Always close the output writer
}
}
}
i then hit: http://localhost:8080/myWebApp/sayhello
and get a 404 error. any ideas as to what i am doing wrong?
myWebApp should live next to ROOT, not inside of it.
Tomcat 7 Deployment