You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by Tammer Salem <sa...@hotmail.com> on 2003/01/11 13:21:15 UTC

Servlet doesn't want to compile

Hi,
I'm having problems compiling my servlets.
I have a servlet called (HelloWorld.java) in a directory (D:\Program Files\Apache Tomcat 4.0\webapps\test\WEB-INF\classes). My javac.exe is in (D:\j2sdk1.4.1_01\bin). I can't get the servlet file to compile. I think my CLASSPATH and Path environment variables are messed up, because I keep on getting the following exceptions:

=================================
HelloWorld.java:2: package javax.servlet does not exist
import javax.servlet.*;
^
HelloWorld.java:3: package javax.servlet.http does not exist
import javax.servlet.http.*;
^
HelloWorld.java:11: cannot resolve symbol
symbol  : class HttpServlet
location: class HelloWorld
public class HelloWorld extends HttpServlet
                                ^
HelloWorld.java:13: cannot resolve symbol
symbol  : class HttpServletRequest
location: class HelloWorld
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

                          ^
HelloWorld.java:13: cannot resolve symbol
symbol  : class HttpServletResponse
location: class HelloWorld
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

                                                      ^
HelloWorld.java:13: cannot resolve symbol
symbol  : class ServletException
location: class HelloWorld
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

                                                                                           ^
6 errors
=================================


and here is the code:
=================================
import java.io.*; 
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet 
{
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
  PrintWriter out = response.getWriter();
  out.println("Hello World");
 }
}
==================================

I can compile regular Java files with no problems. Only when I import any javax. packages do I get errors.
Can anyone please help me?


thanks,
Tammer Salem

Re: Servlet doesn't want to compile

Posted by Jouni Ruokolainen <jo...@kolumbus.fi>.
----- Original Message ----- 
From: "Tammer Salem" <sa...@hotmail.com>
To: "Tomcat Dev List" <to...@jakarta.apache.org>
Sent: Saturday, January 11, 2003 2:21 PM
Subject: Servlet doesn't want to compile


Hi,
I'm having problems compiling my servlets.
I have a servlet called (HelloWorld.java) in a directory (D:\Program Files\Apache Tomcat 4.0\webapps\test\WEB-INF\classes). My javac.exe is in (D:\j2sdk1.4.1_01\bin). I can't get the servlet file to compile. I think my CLASSPATH and Path environment variables are messed up, because I keep on getting the following exceptions:

=================================
HelloWorld.java:2: package javax.servlet does not exist
import javax.servlet.*;
^
HelloWorld.java:3: package javax.servlet.http does not exist
import javax.servlet.http.*;
^
HelloWorld.java:11: cannot resolve symbol
symbol  : class HttpServlet
location: class HelloWorld
public class HelloWorld extends HttpServlet
                                ^
HelloWorld.java:13: cannot resolve symbol
symbol  : class HttpServletRequest
location: class HelloWorld
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

                          ^
HelloWorld.java:13: cannot resolve symbol
symbol  : class HttpServletResponse
location: class HelloWorld
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

                                                      ^
HelloWorld.java:13: cannot resolve symbol
symbol  : class ServletException
location: class HelloWorld
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

                                                                                           ^
6 errors
=================================


and here is the code:
=================================
import java.io.*; 
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet 
{
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
  PrintWriter out = response.getWriter();
  out.println("Hello World");
 }
}
==================================

I can compile regular Java files with no problems. Only when I import any javax. packages do I get errors.
Can anyone please help me?


thanks,
Tammer Salem


Hi I think your problem is CLASSPATH as you said....Read this  : ) I suppose chapter 3 is very good. 

Details on each step are given below. 
1. Create a Development Directory
The first thing you should do is create a directory in which to place the servlets and JSP pages that you develop. This directory can be in your home directory (e.g., C:\Documents and Settings\Your Name\My Documents\ServletDevel on Windows 2000) or in a convenient general location (e.g., C:\ServletDevel). It should not, however, be in the Tomcat deployment directory (e.g., anywhere within install_dir/webapps). 
Eventually, you will organize this development directory into different Web applications (each with a common structure--see More Servlets and JavaServer Pages Chapter 4). For initial testing of your environment, however, you can just put servlets either directly in the development directory (for packageless servlets) or in a subdirectory that matches the servlet package name. Many developers simply put all their code in the server's deployment directory (within install_dir/webapps). I strongly discourage this practice and instead recommend one of the approaches described in the deployment section. Although developing in the deployment directory seems simpler at the beginning since it requires no copying of files, it significantly complicates matters in the long run. Mixing locations makes it hard to separate an operational version from a version you are testing, makes it difficult to test on multiple servers, and makes organization much more complicated. Besides, your desktop is almost certainly not the final deployment server, so you'll eventually have to develop a good system for deploying anyhow. 

2. Make Shortcuts to Start and Stop the Server
Since I find myself frequently restarting the server, I find it convenient to place shortcuts to the server startup and shutdown scripts inside my main development directory or on my desktop. You will likely find it convenient to do the same. 
For example, one way to make these shortcuts is to go to install_dir/bin, right-click on startup.bat, and select Copy. Then go to your development directory, right-click in the window, and select Paste Shortcut (not just Paste). Repeat the process for install_dir/bin/shutdown.bat. On Unix, you would use ln -s to make a symbolic link to startup.sh, tomcat.sh (needed even though you don't directly invoke this file), and shutdown.sh. 

3. Set Your CLASSPATH
Since servlets and JSP are not part of the Java 2 platform, standard edition, you have to identify the servlet classes to the compiler. The server already knows about the servlet classes, but the compiler (i.e., javac) you use for development probably doesn't. So, if you don't set your CLASSPATH, attempts to compile servlets, tag libraries, or other classes that use the servlet API will fail with error messages about unknown classes. The exact location of the servlet JAR file varies from server to server, but with Tomcat it is install_dir/common/lib/servlet.jar. 
Now, in addition to the servlet JAR file, you also need to put your development directory in the CLASSPATH. Although this is not necessary for simple packageless servlets, once you gain experience you will almost certainly use packages. Compiling a file that is in a package and that uses another class in the same package requires the CLASSPATH to include the directory that is at the top of the package hierarchy. In this case, that's the development directory I just discussed. Forgetting this setting is perhaps the most common mistake made by beginning servlet programmers. 

Finally, you should include "." (the current directory) in the CLASSPATH. Otherwise, you will only be able to compile packageless classes that are in the top-level development directory. 

Here are two representative methods of setting the CLASSPATH. They assume that your development directory is C:\ServletDevel. Replace install_dir with the actual base installation location of the server. Also, be sure to use the appropriate case for the filenames. Note that these examples represent only one approach for setting the CLASSPATH. Many Java integrated development environments have a global or project-specific setting that accomplishes the same result. But these settings are totally IDE-specific and won't be discussed here. And, you can also make a script whereby -classpath ... is automatically appended onto calls to javac. 

Windows 98/Me
Put the following in your autoexec.bat. (Note that this all goes on one line with no spaces--it is broken here for readability.) 

set CLASSPATH=.;
              C:\ServletDevel;
              install_dir\common\lib\servlet.jar

Windows NT/2000/XP
You could use the autoexec.bat file as above, but the preferred method is via system settings. Go to the Start menu and select Settings, then Control Panel, then System, then Environment. Then, enter the CLASSPATH value from the previous bullet. 
4. Bookmark the Servlet and JSP API Documentation
Just as no serious programmer should develop general-purpose Java applications without access to the JDK 1.3 or 1.4 API documentation (in Javadoc format), no serious programmer should develop servlets or JSP pages without access to the API for classes in the javax.servlet packages. 
So, open install_dir/webapps/tomcat-docs/servletapi/index.html in your browser and then add it to your bookmarks (Netscape) or favorites (Internet Explorer) list. If Tomcat is running, you can also access the API with http://localhost/tomcat-docs/servletapi/index.html. However, you almost certainly will want access to the API even when the server is not running, so I recommend you open the file directly from disk and bookmark that location. 

      Compile and Test Some Simple Servlets 


OK, so your environment is all set. At least you think it is. It would be nice to confirm that hypothesis. Verifying this involves the following three steps: 

  1.. Testing a packageless servlet 
  2.. Testing a servlet that uses packages 
  3.. Testing a servlet that uses packages and utility classes 
Details on each step are given below. 
Test 1: A Servlet That Does Not Use Packages
The first servlet to try is a basic one: no packages, no utility (helper) classes, just simple HTML output. Rather than writing your own test servlet, you can just download HelloServlet.java and install it in install_dir/webapps/ROOT/WEB-INF/classes. Right-click on the link to download the file to your system. Note: in all versions of Apache Tomcat 4, the location for servlets in the default Web application is install_dir/webapps/ROOT/WEB-INF/classes. However, in later versions of Tomcat, the system doesn't create the directory for you automatically. No problem: just create it yourself. (Remember that case matters: WEB-INF is upper case, classes is lower case.) 
      What about install_dir/classes? 
      "Hey, wait! Shouldn't I use install_dir/classes instead of install_dir/webapps/ROOT/WEB-INF/classes?" 
      Nope. There are two reasons why it is preferable to use install_dir/webapps/ROOT/WEB-INF/classes: 

      1. It is standard. The ROOT directory follows the normal structure of a Web application (see Section 4.2 of More Servlets and JSP): HTML/JSP files go in the main directory, the web.xml file (see Chapter 5 of More Servlets and JSP) goes in WEB-INF, unjarred Java classes go in WEB-INF/classes, and JAR files go in WEB-INF/lib. So, if you use WEB-INF/classes, you are using a structure that works on all servers that support servlets 2.2 and later. OTOH, install_dir/classes is a Tomcat-specific location that is supported on few other servers. 

      2. It is specific to a Web application. Once you become comfortable with the basics, you will almost certainly divide your projects up into separate Web applications (see Chapters 4-6 of More Servlets and JSP). By putting your code in WEB-INF/classes, you are ready for this, since your code is already part of a Web application (the default one for Tomcat). So, the code can easily be to another Web application, and it will not interfere with any future applications. OTOH, install_dir/classes results in code that is shared by all Web applications on your server. This is almost never what you want.
     
If you get compilation errors, go back and check your CLASSPATH settings (see the earlier section on this topic)--you most likely erred in listing the location of the JAR file that contains the servlet classes (i.e., install_dir/common/lib/servlet.jar). Once you compile HelloServlet.java, put HelloServlet.class in install_dir/webapps/ROOT/WEB-INF/classes. After compiling the code, access the servlet with the URL http://localhost/servlet/HelloServlet (or http://localhost:8080/servlet/HelloServlet if you chose not to change the port number as described earlier). You should get a simple HTML page that says "Hello". If this URL fails but the test of the server itself succeeded, you probably put the class file in the wrong directory. 

Test 2: A Servlet That Uses Packages
The second servlet to try is one that uses packages but no utility classes. Again, rather than writing your own test, you can download and install HelloServlet2.java. Since this servlet is in the moreservlets package, it should go in the moreservlets directory both during development and when deployed to the server. If you get compilation errors, go back and check your CLASSPATH settings--you most likely forgot to include "." (the current directory). Once you compile HelloServlet2.java, put HelloServlet2.class in install_dir/webapps/ROOT/WEB-INF/classes/moreservlets. For now, you can simply copy the class file from the development directory to the deployment directory. However, an upcoming section will provide some options for simplifying the deployment process. 
Once you have placed the servlet in the proper directory, access it with the URL http://localhost/servlet/moreservlets.HelloServlet2. You should get a simple HTML page that says "Hello (2)". If this test fails, you probably either typed the URL wrong (e.g., used a slash instead of a dot after the package name) or put HelloServlet2.class in the wrong location (e.g., directly in install_dir/webapps/ROOT/WEB-INF/classes directory instead of in the moreservlets subdirectory). 

Test 3: A Servlet That Uses Packages and Utilities
The final servlet you should test to verify the configuration of your server and development environment is one that uses both packages and utility classes. HelloServlet3.java is a servlet in the moreservlets package that uses the ServletUtilities class to simplify the generation of the DOCTYPE (specifies the HTML version--useful when using HTML validators) and HEAD (specifies the title) portions of the HTML page. Those two parts of the page are useful (technically required, in fact), but are tedious to generate with servlet println statements. 
Since both the servlet and the utility class are in the moreservlets package, they should go in the moreservlets directory. If you get compilation errors, go back and check your CLASSPATH settings--you most likely forgot to include the top-level development directory. I've said it before, but I'll say it again: your CLASSPATH must include the top-level directory of your package hierarchy before you can compile a packaged class that makes use of another class from the same package. This requirement is not particular to servlets; it is the way packages work on the Java platform in general. Nevertheless, many servlet developers are unaware of this fact, and it is one of the (perhaps the) most common errors beginning developers encounter. 

Once you compile HelloServlet3.java (which will automatically cause ServletUtilities.java to be compiled), put HelloServlet3.class and ServletUtilities.class in install_dir/webapps/ROOT/WEB-INF/classes/moreservlets. Then, access the servlet with the URL http://localhost/servlet/moreservlets.HelloServlet3. You should get a simple HTML page that says "Hello (3)". 

      Establish a Simplified Deployment Method 


OK, so you have a development directory. You can compile servlets with or without packages. You know which directory the servlet classes belong in. You know the URL that should be used to access them. (Actually, http://hostname/servlet/ServletName is just the default URL; you can also use the web.xml file to customize that URL. Use of web.xml is discussed in detail in Chapter 5 of More Servlets and JavaServer Pages.) But how do you move the class files from the development directory to the deployment directory? Copying each one by hand every time is tedious and error prone. Once you start using Web applications, copying individual files becomes even more cumbersome. 

There are several options to simplify the process. Here are a few of the most popular ones. If you are just beginning with servlets and JSP, you probably want to start with the first option and use it until you become comfortable with the development process. Note that I do not list the option of putting your code directly in the server's deployment directory. Although this is one of the most common choices among beginners, it scales so poorly to advanced tasks that I recommend you steer clear of it from the start. 

  1.. Copy to a shortcut or symbolic link. 
  2.. Use the -d option of javac. 
  3.. Let your IDE take care of deployment. 
  4.. Use ant or a similar tool. 
Details on these four options are given below. 
1. Copy to a Shortcut or Symbolic Link
Go to install_dir/webapps/ROOT/WEB-INF, right-click on the classes directory, and select Copy. Then go to your development directory, right-click, and select Paste Shortcut (not just Paste). Now, whenever you compile a packageless servlet, just drag the class files onto the shortcut. When you develop in packages, use the right mouse to drag the entire directory (e.g., the moreservlets directory) onto the shortcut, release the mouse, and select Copy. On Unix/Linux, you can use symbolic links (created with ln -s) in a manner similar to that for Windows shortcuts. 
An advantage of this approach is that it is simple. So, it is good for beginners who want to concentrate on learning servlets and JSP, not deployment tools. Another advantage is that a variation applies once you start using your own Web applications. (See Chapters 4-6 of More Servlets and JSP for details on Web applications). For instance, with Tomcat, you can easily make your own Web application by putting a copy of the install_dir/webapps/ROOT directory into your development directory and renaming it (for example, to testApp). Now, to deploy your Web application, just make a shortcut to install_dir/webapps and copy the entire Web application directory (e.g., testApp) each time by using the right mouse to drag the directory that contains your Web application onto this shortcut and selecting Copy (say Yes when asked if you want to replace existing files). Almost everything stays the same as it was without Web applications: just add the name of the directory to the URL after the hostname (e.g., replace http://locahost/blah/blah with http://locahost/testApp/blah/blah). Just note that you'll have to restart the server the very first time you deploy the directory into install_dir/webapps. 

One disadvantage of this approach is that it requires repeated copying if you use multiple servers. For example, I usually have Tomcat, JRun, and ServletExec on my desktop system and regularly test my code with all three servers. A second disadvantage is that this approach copies both the Java source code files and the class files to the server, whereas only the class files are needed. This does not matter on your desktop server, but when you get to the "real" deployment server, you won't want to include the source code files. 

2. Use the -d Option of javac
By default, the Java compiler (javac) places class files in the same directory as the source code files that they came from. However, javac has an option (-d) that lets you designate a different location for the class files. You need only specify the top-level directory for class files--javac will automatically put packaged classes in subdirectories that match the package names. So, for example, I could compile the HelloServlet2 servlet as follows (line break added only for clarity; omit it in real life). 
javac -d install_dir/webapps/ROOT/WEB-INF/classes
         HelloServlet2.java

You could even make a Windows batch file or Unix shell script or alias that makes a command like servletc expand to javac -d install_dir/.../classes. See http://java.sun.com/j2se/1.4/docs/tooldocs/win32/javac.html for more details on -d and other javac options. 
An advantage of this approach is that it requires no manual copying of class files. Furthermore, the exact same command can be used for classes in different packages since javac automatically puts the class files in a subdirectory matching the package. 

The main disadvantage is that this approach applies only to Java class files; it won't work for deploying HTML and JSP pages, much less entire Web applications. 

3. Let Your IDE Take Care of Deployment
Most servlet- and JSP-savvy development environments (e.g., IBM WebSphere Studio, Macromedia JRun Studio, Borland JBuilder) have options that let you tell the IDE where to deploy class files for your project. Then, when you tell the IDE to build the project, the class files are automatically deployed to the proper location (package-specific subdirectories and all). 
An advantage of this approach, at least in some IDEs, is that it can deploy HTML and JSP pages and even entire Web applications, not just Java class files. A disadvantage is that it is an IDE-specific technique and thus is not portable across systems. 

4. Use ant or a Similar Tool
Developed by the Apache foundation's Jakarta project, ant is a tool similar to the Unix make utility. However, ant is written in the Java programming language (and thus is portable) and is touted to be both simpler to use and more powerful than make. Many servlet and JSP developers use ant for compiling and deploying. The use of ant is especially popular among Tomcat users and with those developing Web applications. 
For general information on using ant, see http://jakarta.apache.org/ant/manual/. See http://jakarta.apache.org/tomcat/tomcat-4.1-doc/appdev/processes.html for specific guidance on using ant with Tomcat. 

The main advantage of this approach is flexibility: ant is powerful enough to handle everything from compiling the Java source code to copying files to producing WAR files (MSAJSP Section 4.3). The disadvantage of ant is the overhead of learning to use it; there is more of a learning curve with ant than with the other techniques in this section. 

      More Information 


        a.. Servlet and JSP Short Courses. 
          a.. Programming with Servlet and JSP Technology. Intermediate-level course for those who know Java but not JSP and servlets. 
          b.. Advanced Servlet and JSP Programming. Advanced course for those with moderate to significant previous JSP and servlet experience. 
          c.. On-site courses. Customizable courses taught at your organization. Can include mix of the intermediate and advanced topics. Can also include basic Java topics for developers who don't have much Java experience. 
        b.. Tomcat home page. At Apache Jakarta site. 
        c.. Tomcat 4.0 documentation. 
        d.. Tomcat 4.1 documentation. 
        e.. Servlet 2.3 and JSP 1.2 API. (Javadoc; from Apache site) 
        f.. Contact Marty. Report errors and omissions in this writeup or inquire about training courses. 
     a.. Home Page for More Servlets and JavaServer Pages. Includes the table of contents, index, source code archive, etc. 
        b.. More Servlets and JavaServer Pages at amazon.com. 30% off. 
        c.. Free Examination Copies of More Servlets and JavaServer Pages. For instructors at qualified institutions. 
        d.. Home Page for Core Servlets and JavaServer Pages. Includes the table of contents, index, source code archive, etc. 
        e.. Core Servlets and JavaServer Pages at amazon.com. 30% off. 
        f.. Free Examination Copies of Core Servlets and JavaServer Pages. For instructors at qualified institutions. 
     




--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>