This error occurs when you compile a java program using classes that support the Servlet API. The compiler searches for the library (included in a .jar file) by using the CLASSPATH. You can specify this when you compile using -classpath
or -cp
options as noted in other responses, but you should set up your environment to define the classpath as needed.
Set the CLASSPATH environment variable to reference the location of servlet-api.jar
, which depends on your setup (OS, how you installed, etc.)
Assuming you're using Tomcat and have installed it in one of 20 possible ways, the APIs used by servlets will be installed on your system, relative to wherever Tomcat is installed. For historical reasons, Tomcat is also known as "Catalina", so you can use the command "catalina" to run certain commands, and alone, it will report, amongst other things the CATALINA_BASE
. For example on my Mac using Tomcat installed using homebrew it's
Using CATALINA_BASE: /usr/local/Cellar/tomcat/8.5.9/libexec
The location of the Tomcat servlet libraries is under this in the lib
directory.
Set CATALINA_BASE, then set CLASSPATH using the base as a start, for example for Linux or OSX you might set this in .profile
, or .bash_profile
like so:
export CATALINA_BASE=/usr/local/Cellar/tomcat/8.5.9/libexec
export CLASSPATH=$CATALINA_BASE/lib/servlet-api.jar:$CLASSPATH
Exit the terminal/shell and come back in to run the profile. You should be able to see that the variable is set by using the echo
command, e.g.
echo $CLASSPATH
or in Windows
echo %CLASSPATH%
If it displays the full path to the jar `javac WebTest.java' compile your class.
Other answers are correct -- set up your IDE (Eclipse, IntelliJ) to know about Tomcat or build with Maven and you'll save pain.