import servlet API to eclipse project (javax.servlet cannot be resolved error)


⛔️ The import javax.servlet can't be resolved

import java.servlet cannot be resolved error.png
import java.servlet cannot be resolved error.png

If you receive the above error message in your java files (servlet classes) while working with eclipse IDE then you are most probably missing the API servlet-api.jar file that is needed by your project.

How to resolve javax.servlet error!
  1. Make sure that you have installed Apache Tomcat Server and have configured it to run your Application.
  2. Right Click on your Project folder,
  3. Now click on Properties at the bottom
  4. Right-Click-on-Project-Folder-and-Select-Properties.png
    Right-Click-on-Project-Folder-and-Select-Properties.png
  5. Select Java Build Path on the right.
  6. Go to Library tab.
  7. Click on Add External Library.
  8. Now go to the location where Apache Tomcat has been installed (e.g. : c:\apache-tomcat-7.0.101).
  9. Now go to lib directory and Select servlet-api jar file.
  10. Apply Changes (Save).
  11. Just Clean + Build your project.
  12. The errors must now get resolved.
Add-servlet-api-jar.png
Add-servlet-api-jar.png

Note: Alternatively, you just copy the servlet-api jar file to the lib folder of your project

package com.code2care.org;


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;

public class ServletError extends HttpServlet
{


  /**
   * HTTP doGet request.
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response) 
  throws ServletException, IOException
  {
   
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("");
    out.println("Resolving Servlet Jar exception");
    out.println("");
    out.println("

Get : This works!.

"); out.println(""); out.close(); } /** * HTTP doPost request. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println("Resolving Servlet Jar Exception"); out.println(""); out.println("

Post : This works!.

"); out.println(""); out.close(); } }