javaservletsclasspath

How to compile servlets from command prompt?


I'd like to compile a very basic servlet from command prompt, but it is always unsuccessful and the compiler tells me the following:

 error: package javax.servlet does not exist.

I googled for the solution and I found that I need to include the servlet.jar libraries into my PATH. I believe I did. I strongly believe that the location for those libraries in my computer is:

C:\apache-tomcat-7.0.23\lib\servlet-api.jar\ 

and the end (the relevant part) of my PATH is the following:

%JAVA_HOME%\bin;C:\apache-tomcat-7.0.23\lib\servlet-api.jar\

For me, it looks ok, but it is obviously not. Can anyone tell me what could be the problem?


Solution

  • classpath not path ... and you don't need it as an evironment variable. You can set the classpath for javac with option -cp or -classpath (several other ways are also available). javac uses the environment variable CLASSPATH to look for classes, that can be useful and can also be a source for hard-to-track-down-problems.

    An example to compile a java file that uses a library(that is classes from outside the standard JavaSE) would be:

    javac -classpath C:\apache-tomcat-7.0.23\lib\servlet-api.jar MyTestServlet.java
    

    if your environmental variable CLASSPATH contains libraries you need you might want to do:

    javac -classpath %CLASSPATH%;C:\apache-tomcat-7.0.23\lib\servlet-api.jar MyTestServlet.java
    

    (please be aware that I don't have access to a windows machine, and therefore haven't tested the idiosyncratic parts of the syntax above) (also note that in this example "C:\apache-tomcat-7.0.23\lib\servlet-api.jar" is a jar file and not a directory which it might be from your question on your machine) For command line compiling on windows OS it is a good idea to have the environmental variable JAVA_HOME set correctly and the bin directory of the JDK in the PATH.

    I do however suggest getting to write-compile-execute-deploy via/in an IDE for servlet development before figuring out how to do it with just the JDK from a command line. Java Servlets are not stand-alone executable classes but needs to be deployed into for example tomcat to be tested/used.