Compiling and Installing a Servlet

To compile a servlet, you must first ensure that you have the JAR file containing all Servlet API classes in the CLASSPATH environment variable. The JAR file is distributed with all web containers. Tomcat includes it in a file called servlet-api.jar, located in the common/lib directory. On a Windows platform, you include the JAR file in the CLASSPATH like this (assuming Tomcat is installed in C:\Jakarta\jakarta-tomcat-5):

                  C:/> set CLASSPATH=C:\Jakarta\jakarta-tomcat-5\common\lib\servlet-api.jar;
                  %CLASSPATH%

You can then compile the HelloWorld servlet from Example 19-1 with the javac command, like this:

C:/> javac HelloWorld.java

To make the servlet visible to the container, you can place the resulting class file in the WEB-INF/classes directory for the example application:

                  C:/> copy HelloWorld.class C:\Jakarta\jakarta-tomcat-5\webapps\ora\
                  WEB-INF\classes

The container automatically looks for classes in the WEB-INF/classes directory structure, so you can use this directory for all application class files. The HelloWorld servlet is part of the default package, so it goes in the WEB-INF/classes directory itself. If you use another package, say com.mycompany, you must put the class file in a directory under WEB-INF/classes that mirrors the package structure. In other words, it should be placed in a directory named WEB-INF/classes/com/mycompany. Alternatively, you can package the class files in a JAR file (see the Java SDK documents for details) and ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.