Java15环境下Ubuntu中Eclipse 2020-09 JEE创建Servlet时javax库缺失问题
Hey there, let's figure out why your Eclipse Servlet project can't find the javax libraries when using Java 15, and walk through the fixes step by step:
- Java 15's modular system change: Starting with Java 9, Oracle removed most non-core
javax.*APIs (includingjavax.servletrelated classes) from the default JDK distribution. Java 15, being a post-modularization release, doesn't ship with these classes out of the box—so your code can't locate them unless you explicitly add the dependencies. - Unconfigured Target Runtime in Eclipse: Even though you're using the Eclipse JEE edition, if you didn't specify a Servlet container (like Tomcat) as your project's Target Runtime during setup, Eclipse won't automatically pull in the Servlet API libraries needed for
javax.servletclasses. - Missing Servlet API dependency: Without adding the Servlet API jar (either via build tools or manual configuration), your compiler has no way to access the
javax.servletpackage and its classes.
Pick the method that fits your project setup:
Method 1: Configure Target Runtime (Recommended for traditional Web projects)
- Right-click your Eclipse project → Properties.
- In the left sidebar, select Targeted Runtimes, then check the box next to your locally installed Servlet container (e.g., Apache Tomcat 9—note that Tomcat 10+ uses
jakarta.servletinstead ofjavax.servlet, so stick to Tomcat 9 or lower if you want to keep usingjavax). - Click Apply and Close. Eclipse will automatically add the container's
servlet-api.jarto your project's build path, and the missing javax classes will be recognized.
Method 2: Add Servlet API dependency via Maven (For Maven-managed projects)
If your project uses Maven, add this dependency to your pom.xml (the provided scope tells Maven that the container will supply this jar at runtime):
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency>
Then right-click your project → Maven → Update Project to pull in the dependency.
Method 3: Manually add the Servlet API jar (For non-Maven/Gradle projects)
- Grab the
servlet-api.jarfrom thelibdirectory of your installed Servlet container (e.g., Tomcat 9's lib folder has this file). Alternatively, download the matching version from the official Servlet API distribution. - Create a
libfolder in your Eclipse project, and move the jar file into it. - Right-click the jar file → Build Path → Add to Build Path. Your compiler will now have access to the
javax.servletclasses.
Quick note
If you're using Tomcat 10 or newer, it's migrated to Jakarta EE, which replaces javax.servlet with jakarta.servlet. If you want to use that newer stack, you'll need to update your imports from import javax.servlet.* to import jakarta.servlet.* and switch your dependency to the Jakarta Servlet API.
内容的提问来源于stack exchange,提问作者vico

