Explain Codes LogoExplain Codes Logo

How do I import the javax.servlet / jakarta.servlet API in my Eclipse project?

java
maven
dependency-management
servlet-api
Alex KataevbyAlex Kataev·Oct 23, 2024
TLDR

For Jakarta Servlet API, include it in your Eclipse project by adding its Maven dependency in pom.xml.

<dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>5.0.0</version> <scope>provided</scope> </dependency>

For non-Maven projects, download the jakarta.servlet-api.jar file and drop it into the WebContent/WEB-INF/lib directory. Then, adjust your build path:

  1. Right-click your project > Properties
  2. Go to Java Build Path > Libraries
  3. Click Add External JARs, select the downloaded JAR, Open, Apply.

Maven-ized project setup

Maven simplifies the library management process. By specifying the dependencies within your pom.xml, it handles not only the library downloads but any associated dependencies.

<dependencies> <!-- No more figting library versions by hand, Maven does the work--> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>5.0.0</version> <scope>provided</scope> </dependency> </dependencies>

By setting <scope> to provided, Maven knows the servlet container provides these at runtime — no need to include them in the deployment package.

##Ditching the manual management

Don't manually manage server libraries. By integrating servers in Eclipse and setting scope in Maven to provided, you not only make library management simpler, but you also avoid version conflicts and other pesky problems.

Configuring your server runtime

A server runtime defines the server that operates your application within Eclipse. Link your chosen servlet container (e.g., Tomcat, Jetty) to your Eclipse project for seamless testing and debugging.

// Tell Eclipse: "This is the server I'm using. Do your thing!" ServletContext sc = this.getServletContext();

Jakarta transition

Servlet APIs transition from javax.servlet to jakarta.servlet is a significant change since Jakarta EE 9. Make sure you update this in your project's pom.xml.

Remember version harmony

Ensure the API version used aligns with your server’s Servlet specification version. For instance, use the Servlet 4.0 specification if you're using Tomcat 9.