Can't import javax.servlet.annotation.WebServlet

Vitaly Menchikovsky picture Vitaly Menchikovsky · Sep 29, 2011 · Viewed 115k times · Source

I have started to write app that can run on Google App Engine.
But when I wanted to use my code from Netbeans to Eclipse I had an errors on:

import javax.servlet.annotation.WebServlet;

and

@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})

the errors are:

The import javax.servlet.annotation cannot be resolved
WebServlet cannot be resolved to a type

I tried to import the servlet-api.jar to Eclipse but still the same, also tried to build and clean the project. I don't use Tomcat on my Eclipse only have it on my Netbeans. How can I solve the problem?

Answer

BalusC picture BalusC · Sep 29, 2011

I tried to import the servlet-api.jar to eclipse but still the same also tried to build and clean the project. I don't use tomcat on my eclipse only have it on my net-beans. How can I solve the problem.

Do not put the servlet-api.jar in your project. This is only asking for trouble. You need to check in the Project Facets section of your project's properties if the Dynamic Web Module facet is set to version 3.0. You also need to ensure that your /WEB-INF/web.xml (if any) is been declared conform Servlet 3.0 spec. I.e. the <web-app> root declaration must match the following:

<web-app
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

In order to be able to import javax.servlet stuff, you need to integrate a fullworthy servletcontainer like Tomcat in Eclipse and then reference it in Targeted Runtimes of the project's properties. You can do the same for Google App Engine.

Once again, do not copy container-specific libraries into webapp project as others suggest. It would make your webapp unexecutabele on production containers of a different make/version. You'll get classpath-related errors/exceptions in all colors.

See also:


Unrelated to the concrete question: GAE does not support Servlet 3.0. Its underlying Jetty 7.x container supports max Servlet 2.5 only.