How can I add servlet API dependencies in Eclipse?

I’m trying to work on a web application that uses servlets within Eclipse, but I’m encountering some issues. Whenever I attempt to import classes from the servlet packages, I receive error notifications that indicate Eclipse cannot find the necessary packages.

Here’s a snippet of code to illustrate the issue:

import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class MyWebHandler extends HttpServlet {
    protected void processRequest(HttpServletRequest req, HttpServletResponse resp) {
        // servlet logic here
    }
}

Eclipse highlights the import lines in red and suggests that the packages are missing. What actions should I take to ensure my Eclipse project is set up correctly to include the servlet API? Should I be downloading extra libraries or making specific configurations?

This happens all the time with servlet projects in Eclipse. Servlet API classes aren’t in the standard Java runtime, so you need to add them to your classpath manually. Easiest way is setting up a server runtime in Eclipse - go to Project Properties > Java Build Path > Libraries tab, then add your server runtime library (like Tomcat). This automatically pulls in all the servlet APIs you need. You could also grab the servlet API JARs from Maven Central or your server’s install directory and add them as external JARs, but I’d go with the server runtime setup since it keeps your dev environment in sync with where you’re actually deploying.

yep, that worked for me too! just make sure u add the right jar from your server’s lib folder. once u do that, the imports should be recognized. gl!

I encountered similar issues when I began working with servlets in Eclipse. The servlet APIs are not included by default with the Java Development Kit (JDK), as they are part of the application server. If you’re using Maven, simply include the jakarta.servlet dependency in your pom.xml and set its scope to ‘provided’ since your server will manage it at runtime. For those not using Maven, you can manually download the servlet API JAR from Jakarta EE’s official website and include it through the Properties menu under Java Build Path by selecting Add External JARs. It’s important to note that the namespace has changed to jakarta.servlet, while older servers may still reference javax.servlet.