Close

Servlet 3.0 Annotations

[Last Updated: Aug 28, 2018]
  • In Servlet 3.0, several new annotations were introduced in package javax.servlet.annotation. The configurations we used to do in web.xml, can now be alternatively done by using annotations.
  • Now, we can have Servlet, Filter and ServletContextListener without web.xml.
  • They are intended to provide meta-data only and we still need to extend the corresponding class or implement the corresponding interface.
  • The annotations are scanned in WEB-INF/classes directory or in jar residing in WEB-INF/lib.
  • The scanning is done during deployment time.
  • If there's a lot of jars in WEB-INF/lib then startup of the servlet container could be significantly slow because every single class file in every single JAR file has to be scanned. We can turn off jar scanning for annotation by using metadata-complete="true" in web.xml.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app metadata-complete="true" id="WebApp_ID" version="3.0"...
    That will also turn off discovery of web fragments. We will explain web fragments later.
  • web.xml can still be used to override annotation configurations selectively.
  • Using annotations, we don't have ways to configure things like: providing a list of welcome pages, defining error pages, and giving filters order. There we have to use web.xml.
  • These annotation are introduced to increase developer productivity.
  • They have better defaults and based on convention over configuration paradigm.

Following are the annotations introduced in Servlet 3.0 API

We can summarised the usage of above annotations as follows:
Annotation web.xml equivalent Component Usage
@WebServlet <servlet> Servlet classes typically extending javax.servlet.http.HttpServlet
@WebFilter <filter> Servlet Filter class implementing javax.servlet.Filter
@WebInitParam <init-param> Servlet and Filter classes
@WebListener <listener> Classes implementing:
javax.servlet.ServletContextListener
javax.servlet.ServletContextAttributeListener
javax.servlet.ServletRequestListener javax.servlet.ServletRequestAttributeListener javax.servlet.http.HttpSessionListener javax.servlet.http.HttpSessionAttributeListener javax.servlet.http HttpSessionIdListener javax.servlet.http HttpSessionActivationListener
@MultipartConfig <multipart-config> Servlet classes responsible for file upload on multipart/form-data requests
@ServletSecurity @HttpMethodConstraint @HttpConstraint <security-constraint> Servlet classes specifying security constraints
@HandlesTypes Not available Class implementing javax.servlet.ServletContainerInitializer. This is a new pluggability mechanism introduced in Servlet 3.0.

See Also