[ Team LiB ] Previous Section Next Section

Recipe 1.3 Compiling a Servlet


You have written a servlet, and now you want to compile it into a class file.


Make sure that servlet.jar (for Tomcat 4.1.24) or servlet-api.jar (for Tomcat 5) is on your user classpath. Use javac as you would for any other Java source file.


At a minimum, you have to place the servlet classes on your classpath in order to compile a servlet. These classes are located in these Java packages:

  • javax.servlet

  • javax.servlet.http

Tomcat 5 supports the servlet API 2.4; the JAR file that you need on the classpath is located at <Tomcat-5-installation-directory>/common/lib/servlet-api.jar. Tomcat 4.1.24 uses the servlet 2.3 API. The servlet classes are located at: <Tomcat-4-installation-directory>/common/lib/servlet.jar.

For BEA WebLogic 7.0, the servlet classes and many other subpackages of the javax package (e.g., javax.ejb, javax.mail, javax.sql) are located at: <WebLogic-installation-directory>/weblogic700/server/lib/weblogic.jar.

If you are using Ant to compile servlet classes, then proceed to Recipe 4.4, do not pass Go, do not collect $200. That recipe is devoted specifically to the topic of using Ant to compile a servlet. If you use an IDE, follow its instructions for placing a JAR file on the classpath.

The following command line compiles a servlet in the src directory and places the compiled class, nested within its package-related directories, in the build directory:

javac -classpath K:\tomcat5\jakarta-tomcat-5\dist\common\lib\servlet-api.jar 
      -d ./build ./src/FirstServlet.java

For this command line to run successfully, you must change to the parent directory of the src directory.

Recipe 1.4 explains the typical directory structure, including the src directory, for developing a web application.

If the servlet depends on any other libraries, you have to include those JAR files on your classpath as well. I have included only the servlet-api.jar JAR file in this command line.

You also have to substitute the directory path for your own installation of Tomcat for this line of the prior command-line sequence:


This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software Development Kit (JDK). For this command to work properly, you have to include the location of the Java SDK that you are using in the PATH environment variable. For example, on a Unix-based Mac OS X 10.2 system, the directory path /usr/bin must be included in the PATH variable. On my Windows NT machine, the PATH includes h:\j2sdk1.4.1_01\bin.

See Also

Chapter 2 on deploying servlets and JSPs; Chapter 3 on naming servlets; Recipe 1.4 on packaging servlets and JSPs; Recipe 1.5 on creating the deployment descriptor; the J2EE tutorial from Sun Microsystems: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/J2eeTutorialTOC.html; Jason Hunter's Java Servlet Programming (O'Reilly).

    [ Team LiB ] Previous Section Next Section