English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Servlet Annotations

So far, you have learned how Servlets deploy applications to a web server using a deployment descriptor (web.xml file).  Servlet API 3.0 introduced a new package named javax.servlet.annotation. It provides annotation types that can be used to annotate Servlet classes. If annotations are used, there is no need for a deployment descriptor (web.xml). But you should use tomcat7or any higher version of tomcat.

Annotations can replace the equivalent XML configuration in the Web deployment descriptor (web.xml) such as servlet declarations and servlet mappings. The servlet container will process the annotated classes at deployment time.

Servlet 3The annotation types introduced in version .0 are

Sr.No.Annotation and description
1

@WebServlet

Declares a servlet

2

@WebInitParam

Specifies initialization parameters

3

@WebFilter

Declares a servlet filter

4

@WebListener

Declares a WebListener

5

@HandlesTypes

Declares the class types that the ServletContainerInitializer can handle.

6

@HttpConstraint

This annotation is used in the ServletSecurity annotation to indicate the security constraints to be applied to all HTTP protocol methods, for which there is no corresponding HttpMethodConstraint element in the ServletSecurity annotation.

7

@HttpMethodConstraint

This annotation is used in the ServletSecurity annotation to represent the security constraints of a specific HTTP protocol message.

8

@MultipartConfig

An annotation that can be specified on the Servlet class, indicating that the Servlet instance expects to be multipart/Request with form data MIME type

9

@ServletSecurity

This annotation is used for Servlet implementation classes to specify the security constraints that the Servlet container implements for HTTP protocol messages.

We have discussed some annotations in detail here.

@WebServlet

@WebServlet is used to declare the configuration of a Servlet with the container. The following table contains the list of properties used in the WebServlet annotation.

Sr.No.Properties and descriptions
1

String name

Name of the Servlet

2

String[] value

Array of URL patterns

3

String[] urlPatterns

Array of URL patterns to apply this filter

4

Int loadOnStartup

The integer value gives the startup sorting hint

5

WebInitParam[] initParams

Servlet initializes array parameters

6

Boolean asyncSupported

Asynchronous operations supported by the Servlet

7

String smallIcon

Small icon of the Servlet, if available

8

String largeIcon

Large icon of the Servlet, if available

9

String description

Description of the Servlet, if available

10

String displayName

Display the name of this Servlet (if available)

At least one URL pattern must be declared in the value or urlPattern property of the annotation, but both properties cannot be declared at the same time.

When the URL pattern is the only property to be set, it is recommended to use the value property; otherwise, the urlPattern property should be used.

Online Example

The following example describes how to use the @WebServlet annotation. It is a simple servlet that displays the text Hello servlet.

import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebInitParam; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
@WebServlet(value = "/Simple 
public class Simple extends HttpServlet {
   private static final long serialVersionUID = 1L; 
   protected void doGet(HttpServletRequest request, HttpServletResponse response)  
      throws ServletException, IOException { 
   
      response.setContentType("text/html   
      PrintWriter out = response.getWriter();   
      out.print("<html><body>");   
      out.print("<h3>Hello Servlet</h3>   
      out.print("</body></html>         
   }   
}

Compile Simple.java in the usual way and place the class file in <tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

Now try to run http://localhost:8080/Simple call any servlet. You will see the following output on the web page.

Hello servlet

@WebInitParam

@WebInitParam annotation is used to specify initialization parameters for Servlet or Filter. It is used in WebFilter or webevlet annotations. The following table contains the list of properties used in the WebInitParam annotation.

Sr.No.Properties and descriptions
1

String name

Name of initialization parameters

2

String value

Value of initialization parameters

3

String description

Description of initialization parameters

Online Example

@WebInitParam annotation is used to specify initialization parameters for Servlet or Filter. It is used in WebFilter or webevlet annotations. The following table contains the list of properties used in the WebInitParam annotation.

import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebInitParam; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse;
@WebServlet(value = "/Simple", initParams = { 
   @WebInitParam(name = "foo", value = "Hello "), 
   @WebInitParam(name = "bar", value = " World!") 
}) 
public class Simple extends HttpServlet {
   private static final long serialVersionUID = 1L; 
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {   
      
      response.setContentType("text/html   
      PrintWriter out = response.getWriter();   
      out.print("<html><body>");   
      out.print("<h3>Hello Servlet</h3>   
      out.println(getInitParameter("foo")); 
      out.println(getInitParameter("bar")); 
      out.print("</body></html>         
   }   
}

Compile Simple.java in the usual way and place the class file in <tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

Now try to run http://localhost:8080/Simple call any servlet. You will see the following output on the web page.

Hello Servlet
Hello World!

@Webfilter

This is an annotation used to declare servlet filters. It is processed by the container at deployment time and applies the corresponding filter to the specified URL patterns, servlets, and dispatcher types.

@WebFilter annotation defines filters in the web application. This annotation is specified on the class and contains metadata about the declared filter. The annotated filter must specify at least one URL pattern. The following table lists the properties used for the WebFilter annotation.

Sr.No.Properties and descriptions
1

String filterName

The name of the filter

2

String[] urlPatterns

Provide the value of the application filter or the urlPatterns array

3

DispatcherType[] dispatcherTypes

Specify the scheduler (request/The type of the response)

4

String[] servletNames

Provide an array of servlet names

5

String displayName

The name of the filter

6

String description

Filter description

7

WebInitParam[] initParams

The initialization array parameters of this filter

8

Boolean asyncSupported

The asynchronous operations supported by the filter

9

String smallIcon

The small icon of the filter (if available)

10

String largeIcon

The large icon of the filter (if available)

Online Example

The following example shows how to use the @WebFilter annotation. It is a simple LogFilter that displays Init param test param's value and the current timestamp. This means that the filter works like an interface layer between request and response. Here we use "/*" represents urlPattern. This means that the filter applies to all servlets.

import java.io.IOException; 
import javax.servlet.annotation.WebFilter; 
import javax.servlet.annotation.WebInitParam; 
import javax.servlet.*; 
import java.util.*;  
//Implement filter class
@WebFilter(urlPatterns = {"/*}, initParams = { 
   @WebInitParam(name = "test-param", value = "Initialization Paramter")}) 
public class LogFilter implements Filter {
   
   public void init(FilterConfig config) throws ServletException { 
      // get initialization parameter
      String testParam = config.getInitParameter("test-param");
            
      //print init parameter
      System.out.println("Test Param: " + testParam);  
   } 
   public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException { 
	  
      //Record the current timestamp.
      System.out.println("Time " + new Date().toString());  
         
      //Pass the request back to the filter chain
      chain.doFilter(request,response); 
   }
   public void destroy( ) {
      /* Call before deleting the filter instance
      Services provided by the web container*/ 
   } 
}

Compile Simple.java in the usual way and place the class file in <tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

Now try to run http://localhost:8080/Simple call any servlet. You will see the following output on the web page.

Hello Servlet
  
Hello World!

Now, open the servlet console. There, you will find the initialized parameter testparam and the current timestamp along with the servlet's notification message.