@WebServlet annotation with Tomcat 7

Provided that you’re sure that you’re using Tomcat 7 or newer, the webapp’s web.xml has to be declared conform Servlet 3.0 spec in order to get Tomcat to scan and process the annotations. Otherwise Tomcat will still run in a fallback modus matching the Servlet version in web.xml. The support for servlet API annotations was only added in Servlet 3.0 (Tomcat 7).

So, the root declaration of your web.xml must look like below (make sure you remove any DOCTYPE from web.xml too, otherwise it will still be interpreted as Servlet 2.3!).

<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">

Further, there’s a minor difference in the URL pattern. The URL pattern /notifications will let the servlet only listen on requests on exactly that path. It does not kick in on requests with an extra path like /notifications/list or something. The URL pattern /notifications/* will let the servlet listen on requests with extra path info as well.

The minimum @WebServlet annotation should thus look like this

@WebServlet("/notifications/*")

The rest of attributes are optional and thus not mandatory to get the servlet to function equally.

See also:

Leave a Comment