How to compile a servlet for Tomcat in command lin

2020-02-29 10:53发布

问题:

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.

回答1:

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


回答2:

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!



回答3:

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


回答4:

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.