Search code examples
javatomcatservletscompiler-errorsosx-mountain-lion

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.


Solution

  • 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