In my application, I had a servlet which was defined like this in the web.xml:
<servlet>
<display-name>Notification Servlet</display-name>
<servlet-name>NotificationServlet</servlet-name>
<servlet-class>com.XXX.servlet.NotificationServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>NotificationServlet</servlet-name>
<url-pattern>/notification/*</url-pattern>
</servlet-mapping>
After moving to use Tomcat 7, I would like to use the @WebServlet annotation that will do the job.
Here is the way I did it:
@WebServlet( name="NotificationServlet", displayName="Notification Servlet", urlPatterns = {"/notification"}, loadOnStartup=1)
public class NotificationServlet extends HttpServlet {
And it does not work.
Could someone please tell me what I did wrong?
Provided that you’re sure that you’re using Tomcat 7 or newer, the webapp’s
web.xmlhas 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 inweb.xml. The support for servlet API annotations was only added in Servlet 3.0 (Tomcat 7).So, the root declaration of your
web.xmlmust look like below (make sure you remove anyDOCTYPEfromweb.xmltoo, otherwise it will still be interpreted as Servlet 2.3!).Further, there’s a minor difference in the URL pattern. The URL pattern
/notificationswill let the servlet only listen on requests on exactly that path. It does not kick in on requests with an extra path like/notifications/listor something. The URL pattern/notifications/*will let the servlet listen on requests with extra path info as well.The minimum
@WebServletannotation should thus look like thisThe rest of attributes are optional and thus not mandatory to get the servlet to function equally.
See also: