Getting a basic Hello World servlet up and running is not an easy task, primarily because much of information on the Web is out of date, and because servlet container implementations are not as standardized as they could be. In this entry, I get a basic Tomcat servlet up and running, and point out some of the traps and pitfalls I encountered along the way.
Most older tutorials will say that servlets are automatically and dynamically loaded if /servlet is specified before the name of the servlet. That’s not entirely true. In recent versions of Tomcat, the run-time invoker is disabled by default due to potential security risks. But in my opinion, it’s perfectly acceptable to enable in a testing environment when you’re twiddling with code. To turn it on, uncomment the following from server.xml:
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
Also uncomment the servlet mapping:
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
The servlet itself is not difficult to write. Place HelloWorldServlet.java in your WEB-INF/classes directory, though be sure to first setup a web context:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>HelloWorldServlet</title>");
out.println("</head>");
out.println("<body><h1>Hello World</h1></body>");
out.println("</html>");
}
}
To compile, use the CLASSPATH option and point it to the servlet-api jar file distributed with your Tomcat installation. Tomcat 5 on Linux Step-by-Step is an excellent resource for additional information.