356

I want to develop with Servlets in Eclipse, but it says that the package javax.servlet / jakarta.servlet cannot be resolved. How can I add javax.servlet / jakarta.servlet package to my Eclipse project?

1
  • im trying to run a simple hello word type servlet, normally if i wanted to make a gui i would import java......swing.*; i cant find the right import for a servlet
    – tom
    Commented Nov 2, 2010 at 10:11

17 Answers 17

456

Ensure you've the right Eclipse and Server version

Ensure that you're using at least Eclipse IDE for Enterprise Java (and Web) developers (with the Enterprise). It contains development tools to create dynamic web projects and easily integrate servletcontainers (those tools are part of Web Tools Platform, WTP). In case you already had Eclipse IDE for Java (without Enterprise), and manually installed some related plugins, then chances are that it wasn't done properly. You'd best trash it and grab the real Eclipse IDE for Enterprise Java one.

You also need to ensure that you already have a servletcontainer installed on your machine which implements at least the same Servlet API version as the servletcontainer in the production environment, for example Apache Tomcat, RedHat WildFly, Eclipse GlassFish, etc. Usually, just downloading the ZIP file and extracting it is sufficient. In case of Tomcat, do not download the EXE format, that's only for Windows based production environments. See also a.o. Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use.

A servletcontainer is a concrete implementation of the Servlet API. Also note that for example WildFly and GlassFish are more than just a servletcontainer, they also support JSF (Faces), EJB (Enterprise Beans), JPA (Persistence) and all other Jakarta EE fanciness. See also a.o. What exactly is Java EE?

Ensure that you're using the right Servlet package

The javax.* package has been renamed to jakarta.* package since Servlet API version 5.0 which is part of Jakarta EE 9 (Tomcat 10, TomEE 9, WildFly 22 Preview, GlassFish 6, Payara 6, Liberty 22, etc). So if you're targeting these server versions or newer, then you need to replace

import javax.servlet.*;
import javax.servlet.http.*;

by

import jakarta.servlet.*;
import jakarta.servlet.http.*;

in order to get it to compile, else you might risk to face this build error

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Integrate Server in Eclipse and associate it with Project

Once having installed both Eclipse for Enterprise Java and a servletcontainer on your machine, do the following steps in Eclipse:

  1. Integrate servletcontainer in Eclipse

    a. Via Servers view

    • Open the Servers view in the bottom box.

    • Rightclick there and choose New > Server.

    • Pick the appropriate servletcontainer make and version and walk through the wizard.

      enter image description here

    b. Or, via Eclipse preferences

    • Open Window > Preferences > Server > Runtime Environments.

    • You can Add, Edit and Remove servers here.

      enter image description here

  2. Associate server with project

    a. In new project

    • Open the Project Navigator/Explorer on the left hand side.

    • Rightclick there and choose New > Project and then in menu Web > Dynamic Web Project.

    • In the wizard, set the Target Runtime to the integrated server.

      enter image description here

    b. Or, in existing project

    • Rightclick project and choose Properties.

    • In Targeted Runtimes section, select the integrated server.

      enter image description here

    Either way, Eclipse will then automatically take the servletcontainer's libraries in the build path. This way you'll be able to import and use the Servlet API.

Never carry around loose server-specific JAR files

You should in any case not have the need to fiddle around in the Build Path property of the project. You should above all never manually copy/download/move/include the individual servletcontainer-specific libraries like servlet-api.jar, jsp-api.jar, el-api.jar, j2ee.jar, javaee.jar, etc. It would only lead to future portability, compatibility, classpath and maintainability troubles, because your webapp would not work when it's deployed to a servletcontainer of a different make/version than where those libraries are originally obtained from.

In case you're using Maven, you need to make absolutely sure that servletcontainer-specific libraries which are already provided by the target runtime are marked as <scope>provided</scope>. You can find examples of proper pom.xml dependency declarations for Tomcat 10+, Tomcat 9-, JEE 9+ and JEE 8- in this answer: How to properly configure Jakarta EE libraries in Maven pom.xml for Tomcat?

Here are some typical exceptions which you can get when you litter the /WEB-INF/lib or even /JRE/lib, /JRE/lib/ext, etc with servletcontainer-specific libraries in a careless attempt to fix the compilation errors:

8
  • 4
    @BalusC If I am using Apache Ant to build my project, how do I include the /lib(servlet-api.jar & jsp-api.jar) folder of servlet container dynamically ? Or do I need to hard code the path to the /lib folder like - <property name="tomcat.home" value="D:\\Program Files\\Apache Software Foundation\\apache-tomcat-6.0.36"/> etc Commented Jun 13, 2013 at 15:13
  • 2
    @BalusC why are maven projects created with archetype maven-archetype-webapp not including the servlet-api JAR as a dependency? The project has an index.jsp with compile error. (Eclipse Luna Build id: 20140612-0600, JDK 8, M2eclipse)
    – arun
    Commented Sep 20, 2014 at 5:56
  • 1
    @arun servlet-api dependencies are provided by the Servlet runtime environments like Tomcat, Wildfly, Glassfish, etc.,. Don't ever include it as part of your app, as there's a good possibility of it clashing with the environment's.
    – asgs
    Commented Sep 23, 2015 at 9:27
  • @BalusC, 1) Is javax.servlet-api-3.1.0.jar equal to tomcat8/lib/servlet-api.jar? I decompile the two jars, then find moust of the classes/interfaces are the same. 2) Is javax.servlet-api-3.1.0.jar container-neutral(not servletcontainer-specific libraries)?
    – gfan
    Commented Oct 28, 2016 at 11:23
  • 1
    @BalusC, What you saying is some kind of abstract for me. I am new to Java. Maybe I still don't understand some concept of Java. So, could you please give me a feedback of the previous commnet of my questions. And I would like to append some clarification for my question: From my thinking, JCP(or Oracle) will provide a jar, which only contains interfaces of Servlet, for example the jar of javax.servlet-api-3.1.0.jar. The other vendors who want to deliever their own Servlet should implement the interfaces(another choice is they follow the JCP doc, then give their own interface and implement)
    – gfan
    Commented Oct 28, 2016 at 12:59
231

import javax.servlet

STEP 1

Go to properties of your project ( with Alt+Enter or righ-click )

STEP 2

check on Apache Tomcat v7.0 under Targeted Runtime and it works.

6
  • 2
    Helped me add my JBOSS runtime. My list was empty.
    – span
    Commented Jan 17, 2014 at 13:35
  • 2
    This was the solution for me. I had set tomcat 6.0 as my deployment enviournment(as a server in eclipse), but neglected to specify it as my runtime enviournment... I'm guessing that means it could find the .jars in my tomcat/lib folder at runtime, but not at compile time.
    – Paul
    Commented Mar 18, 2014 at 10:29
  • Thanks! But how can I delete copies of mu servers? I have Apache Tomcat v7.0 (2) and (3) that I want to delete. Anyone knows how?
    – Robben
    Commented May 26, 2015 at 0:56
  • Not helped me to solve problem with The import javax.servlet cannot be resolved.
    – mrgloom
    Commented Apr 21, 2017 at 12:08
  • 1
    This works! Thanks, @mrgloom, you may want to remove the server and create a new server in your localhost Commented May 1, 2017 at 23:17
85

Little bit difference from Hari:

Right click on project ---> Properties ---> Java Build Path ---> Add Library... ---> Server Runtime ---> Apache Tomcat ----> Finish.

1
  • 3
    Hi ivanLam, Apache Tomcat is not showing after Server Runtime? What to do now! Commented Dec 10, 2015 at 6:43
19

Add javax.servlet dependency in pom.xml. Your problem will be resolved.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
0
18

Include servlet-api.jar from your server lib folder.enter image description here

Do this step

enter image description here

1
  • 1
    Solution is not working for me still getting below error A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/messenger]] Commented Mar 25, 2017 at 9:49
13

Quick Fix- This worked in Eclipse - Right Click on project -> Properties -> Java Build Path (Tab) -> Add External JARs -> locate the servlet api jar implementation (if Tomcat - its named servlet-api.jar) -> click OK. That's it !!

1
  • 14
    With reference to above BalusC post never manually copy/download/move/include the individual servletcontainer-specific libraries like servlet-api.jar, jsp-api.jar, el-api.jar, j2ee.jar, javaee.jar, etc. It would only lead to future portability, compatibility, classpath and maintainability troubles. Commented Feb 6, 2013 at 16:17
6

For maven projects add following dependancy :

<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Reference

For gradle projects:

dependencies {
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
}

or download javax.servlet.jar and add to your project.

5

you can simply copy the servlet-api.jar and copy that jar files into lib folder, which is in WEB-INF. then just clean and built your project, your errors will be solved.

  **OR**

you can directly add jar files to library by using following steps.

  1. Right click on project.
  2. Go To Properties.
  3. Go to Java Build Path.
  4. Select Add Library option from tabs.
  5. Add Jar Files
  6. give path of your servlet-api.jar file.
  7. Clean and build your project.
1
  • Downvoting, with reference to above BalusC post and Aniket Kulkarni comment, never manually copy/download/move/include the individual servletcontainer-specific libraries like servlet-api.jar, jsp-api.jar, javaee.jar, etc. It would only lead to future portability, compatibility, classpath and maintainability troubles.
    – el-teedee
    Commented Sep 8, 2018 at 19:34
5

I know this is an old post. However, I observed another instance where in the project already has Tomcat added but we still get this error. Did this to resolve that:
Alt + Enter
Project Facets
On the right, next to details, is another tab "Runtimes". The installed tomcat server will be listed there. Select it.
Save the configuration and DONE!

Hope this helps someone.

3

From wikipedia.

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
                "Transitional//EN\">\n" +
                "<html>\n" +
                "<head><title>Hello WWW</title></head>\n" +
                "<body>\n" +
                "<h1>Hello WWW</h1>\n" +
                "</body></html>");
  }
}

This, of course, works only if you have added the servlet-api.jar to Eclipse build path. Typically your application server (e.g Tomcat) will have the right jar file.

3

I was getting a null pointer exception during project creation related to "Dynamic Web Module".

To get the project to compile (that is, to javax.servlet to import successfully) I had to go to project's Properties, pick Project Facets in the sidebar, tick Dynamic Web Module and click Apply.

Surprisingly, this time "Dynamic Web Module" facet installed correctly, and import started to work.

1
  • To add to this, for Tomcat 10.x, I changed Project Facet setting for the "Dynamic Web Module" to a newer one. In my case, this changed to version 5.0 after which the index.jsp file no longer showed an issue on the html tag. Prior to this it was configured to 2.3 (i.e. pre-jakarata) which was not applicable for Tomcat 10.x which leverages the jakarta namespace instead of the java namespace.
    – ebresie
    Commented Oct 16, 2022 at 14:29
3

In my case, when I went to the Targetted Runtimes, screen, Tomcat 7 was not listed (disabled) despite being installed.

To fix, I had to go to Preferences->Server->Runtime Environments then uninstall and reinstall Tomcat 7.

2

Many of us develop in Eclipse via a Maven project. If so, you can include Tomcat dependencies in Maven via the tomcat-servlet-api and tomcat-jsp-api jars. One exists for each version of Tomcat. Usually adding these with scope provided to your POM is sufficient. This will keep your build more portable.

If you upgrade Tomcat in the future, you simply update the version of these jars as well.

1

This could be also the reason. i have come up with following pom.xml.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

The unresolved issue was due to exclusion of spring-boot-starter-tomcat. Just remove <exclusions>...</exclusions> dependency it will ressolve issue, but make sure doing this will also exclude the embedded tomcat server.

If you need embedded tomcat server too you can add same dependency with compile scope.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>compile</scope>
</dependency>
0

You should above all never manually copy/download/move/include the individual servletcontainer-specific libraries like servlet-api.jar

@BalusC,

I would prefer to use the exact classes that my application is going to use rather than one provided by Eclipse (when I am feeling like a paranoid developer).

Another solution would be to use Eclipse "Configure Build Path" > Libraries > Add External Jars, and add servlet api of whatever Container one chooses to use.

And follow @kaustav datta's solution when using ant to build - have a property like tomcat.home or weblogic.home. However it introduces another constraint that the developer must install Weblogic on his/her local machine if weblogic is being used ! Any other cleaner solution?

0

Assume a simple dynamic Web Project. Ensure Tomcat is present on the project's build path.

First get the local tomcat instance downloaded/installed on your machine. Assume we installed tomcat v8.5.

Now configure the Eclipse Global Server Run time Environment

Windows > Preferences > Server > Runtime Environments > Add > Apache > Apache Tomcat v8.5 > Next > Browse Tomcat Installation directory > Next > Finish.

Now create your dynamic web project and we see the import javax.servlet cannot be resolved issue. Resolve this by following below.

Right Click On Project > Build Path > Configure Build Path > Libraries > Add Library > Server Runtime > Select your Apache Tomcat instance > Finish > Apply and Close.

All Errors will be gone.

0

ISSUE
Description Resource Path Location Type The default superclass, "javax.servlet.http.HttpServlet", according to the project's Dynamic Web Module facet version (2.3), was not found on the Java Build Path. index.jsp /FileUploadDemo/src/main/webapp line 1 JSP Problem

Eclipse IDE

  • eclipse-jee-2023-12-R-win32-x86_64
  • Version: 2023-12 (4.30.0)
  • Build id: 20231201-2043

Created a maven project with the following archtype

Catalog: Internal
ArtifactID: maven-archetype-webapp
Version: 1.0

Fixed the issue by upgrading the versions of Dynamic Web Module and Java version

enter image description here

Not the answer you're looking for? Browse other questions tagged or ask your own question.