[Solved] HttpServlet cannot be resolved to a type
- Details
- Written by Nam Ha Minh
- Last Updated on 28 June 2019   |   Print Email
When creating a new Java Servlet in Eclipse IDE, you may encounter the following errors:
HttpServlet cannot be resolved to a type HttpServletRequest cannot be resolved to a type HttpServletResponse cannot be resolved to a type ServletException cannot be resolved to a type The import javax.servlet cannot be resolved WebServlet cannot be resolved to a type
It looks something like this screenshot in Eclipse:
The reason is the Java Servlet API is missing in the project’s classpath. You can solve this problem by specifying a server runtime for the project, e.g. Apache Tomcat runtime – because a Java web server is a servlet container that implements the Servlet API.
In Eclipse, right click on the project, click Properties. In the project properties dialog, click Java Build Path, and click the button Add Library… as shown below:
In the Add Library dialog appears, select Server Runtime:
Click Next. In the next screen select Apache Tomcat and click Finish:
If you don’t see any Apache Tomcat servers here, probably you haven’t installed Tomcat nor added to Eclipse. So follow this tutorial to add Tomcat in Eclipse.
Click Finish to close the Server Library dialog, and you will see the server library Apache Tomcat appears:
Then click Apply and Close, the errors will be gone.
In case you use Maven, the solution would be simpler. Just add a dependency for Java Servlet API in the pom.xml file like this:
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency>
Save the file and wait for seconds for Maven to update the project. You will see the errors are gone way.
NOTE: To avoid this error in future, you should select the Target Runtime as Apache Tomcat when creating the project in Eclipse:
Other Java Servlet Tutorials:
- Java Servlet for beginners (XML)
- Java Servlet for beginners (Annotation)
- Java Servlet and JSP Hello World Tutorial with Eclipse, Maven and Apache Tomcat
- How to use Session in Java web application
- How to use Cookies in Java web application
- Java File Upload Example with Servlet
- Java File Download Servlet Example
Comments