AWG Blogs

Thursday, April 18, 2013

Tomcat Hello World Servlet

Here's a no-IDE quick-start how-to. Create the following directories:

c:\users\John Smith\Documents\scratch\helloTomcat\src
c:\users\John Smith\Documents\scratch\helloTomcat\dist\WEB-INF

open NotePad++ and create the following two files.

c:\users\John Smith\Documents\scratch\helloTomcat\dist\WEB-INF\web.xml

<!DOCTYPE web-app PUBLIC
  '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'
  'http://java.sun.com/dtd/web-app_2_3.dtd'>
<web-app>
  <servlet>
    <servlet-name>mihello</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>mihello</servlet-name>
    <url-pattern>/mihello</url-pattern>
  </servlet-mapping>
</web-app>
c:\users\John Smith\Documents\scratch\helloTomcat\src\HelloServlet.java
import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

public class HelloServlet extends HttpServlet {
  public void doGet (HttpServletRequest req,
                                         HttpServletResponse res)
        throws ServletException, IOException
  {
        PrintWriter out = res.getWriter();
        out.println("Hello, You!");
        out.close();
  }
}
Open a command prompt
C:\Users\John Smith\Documents\scratch\helloTomcat\src>javac -cp "C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar" HelloServlet.java
C:\Users\John Smith\Documents\scratch\helloTomcat\src>mkdir ..\dist\WEB-INF\classes
C:\Users\John Smith\Documents\scratch\helloTomcat\src>copy *.class ..\dist\WEB-INF\classes
C:\Users\John Smith\Documents\scratch\helloTomcat\src>cd ..\dist
C:\Users\John Smith\Documents\scratch\helloTomcat\dist>jar cvf web-arc-test.war
Open a command prompt as Administrator
C:\Users\John Smith\Documents\scratch\helloTomcat\dist>copy web-arc-test.war "C
:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps"
open browser and browse to http://localhost:8085/web-arc-test/mihello
Note: change port to whatever tomcat is running on.
Refs:
http://keyboardsamurais.de/2004/01/15/tomcat_tutorial_helloworld_for_complete_fools_-_english/
http://stackoverflow.com/questions/7924687/compiling-a-simple-hello-world-servlet-into-a-war-for-tomcat
http://www.avajava.com/tutorials/lessons/how-do-i-create-a-war-file-using-the-jar-command.html

No comments:

Post a Comment