简体   繁体   中英

How to compile a servlet for Tomcat in command line? error: package javax.servlet does not exist

I've got this error message when I compiled a Java file :

error: package javax.servlet does not exist

I installed a big .SH file for Jave EE SDK, a Java version gives me this:

java version "1.7.0_10"
Java(TM) SE Runtime Environment (build 1.7.0_10-b18)
Java HotSpot(TM) 64-Bit Server VM (build 23.6-b04, mixed mode)

Do I need to install something else?

I am using Tomcat 7 as a Servlet Container located in /Library/Tomcat/ and simple text editor with the command line.

You need to include the servlet-api JAR in the compile time classpath.

If you are using maven add this as a dependency in the pom.xml.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>

That wil include the dependency at compile time and use the Tomcat one at runtime.

If not you should add Tomcat as project target runtime through Eclipse.

This questions has some useful info on including these in an Eclipse project: How do I import the javax.servlet API in my Eclipse project?

If you are using command line to build the project, you will most likely need to add these to the classpath argument to javac to add these jars to the classpath.

See this question: How to compile servlets from command prompt?

The key part is:

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

A Windows User:

I faced this problem myself and here is the solution that worked fine

Just Add this path to your CLASSPATH environmental variable "C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0\\lib\\servlet-api.jar"

The path before the jar name can differ based on your installation. Just go to your lib folder of tomcat and copy the whole directory.

More info for beginners: You can find Environmental variables here MyComputer -> Properties ->Advanced Settings -> Advanced tab

Now you can simply go to cmd prompt and type "javac Myclass.java"

Hope this helps!

javac -classpath /Library/Tomcat/lib/servlet-api.jar *.java

Read about java class paths here on Wikipedia .

Ready closely the last paragraph under "Overview and architecture".

In your example

The javax.servlet package is not part of the bootstrapped or extension packages, so it must be added manually to your classpath. ALJI has shown you how to do this from the command line. The Wikipedia link above also provides examples.

Recommendation

Everyone hits these types issues when starting a new language. Google is full of tutorials that will help you gain a basic understanding of Java class paths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM