Annotations in Servlet

As of now, We have seen Servlet uses a web.xml file for mapping and deploying our web application to the server. sometimes it becomes monotonous for us to update the web.xml file for every servlet that we create.

So, for that Servlet API 3.0 introduced a separate package called javax.servlet.annotation.It provides annotation types for annotating a servlet class. In order to start let us see what is annotation first.

What is an annotation?

Annotation in a simple term is extra information added to the document. It can be a comment or a note. In Today’s programming world annotation has replaced the traditional pattern of writing programs.

What is Servlet Annotation?

Annotation is the metadata. If we use annotation in servlet so we will not need a web.xml file in our servlet. It will provide the mapping of the URL pattern also. Servlet Container is responsible for processing the annotated classes in servlet. We use @ symbol for annotation. The following are the annotation introduced in Servlet 3.0.

  • @WebServlet: It is used to declare a servlet.
  • @WebInitParam: It is used to specify an Init Parameter.
  • @WebFilter: It is used to specify a Filter.
  • @WebListener: It is used to declare the Listener.
  • @HandlesTypes: It will declare the type of class that web container will handle.
  • @HttpConstraint: It is used to apply security constraints to the HTTP protocol.
  • @HttpMethodConstarint: It is also used to apply security constraints to a specific HTTP protocol.
  • @MultipartConfig: It indicates an object of the servlet expects requests should come from data MIME type.
  • @ServletSecurity: It is used to specify servlet security by servlet container on the HTTP protocol.

Let’s see some of the Annotations

@WebServlet

It is used to declare a servlet in an application. There are some attributes used for WebServlet let us look at it.

  • String name: Name of the servlet.
  • String[] value:array of URL pattern.
  • String[] urlPatterns:Array of URL pattern for filter.
  • int LoadOnStartup: It gives the startup ordering hint.
  • WebInitParam[] initParam:Array of Initialization parameters.
  • Boolean asyncSupported: It is used for asynchronous operation in servlet.
  • String smallIcon: Small icon for this servlet.
  • String largeIcon:LargeIcon for this servlet.
  • String description: Description of the servlet.
  • String displayName: Display the name of the servlet.

Let’s see the simple Example of @WebServlet Annotation

@WebServlet("/HelloAnnotation")
public class HelloAnnotation extends HttpServlet {
  private static final long serialVersionUID = 1L;
    public HelloAnnotation() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
     response.setContentType("text/html");   
        PrintWriter out = response.getWriter();   
        out.print("<html><body>");   
        out.print("<h1>Hello Servlet!!! Now use Annotation</h1>");   
        out.print("</body></html>"); 
  }
}

Output:

@WebInitParam

For InitPrameter we have used <init-param> element in web.xml file.The @WebInitParam annotation is used for specifying an initialization parameter for a servlet or a filter. There are some attributes used for WebInitParam let us look at it.

  • String name:name of init parameer
  • String value: the value of the init parameter.
  • String description: description of the init parameter.

Let’s see the simple Example of @WebInitParam Annotation

@WebServlet(value = "/WebInitParamExample", initParams = { @WebInitParam(name = "name", value = "Nicolas"),
    @WebInitParam(name = "rollno", value = "21") })
public class WebInitParamExample extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public WebInitParamExample() {
    super();
    // TODO Auto-generated constructor stub
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    PrintWriter printWriter = response.getWriter();
    printWriter.println("<html><body>");
    printWriter.println("<h1>With Annotation :-)</h1>");
    printWriter.println("<h1> Name:" + getInitParameter("name") + "</h1>");
    printWriter.println("<h1> ROll No:" + getInitParameter("rollno") + "</h1>");
    printWriter.println("</body></html>");
  }

Output: