Servlet Annotations

Servlet Annotations with Examples

In this article, I am going to discuss Servlet Annotations with Examples. Please read our previous article where we discussed Exception Handling in Servlet with Examples. At the end of this article, you will understand the following pointers in detail.

  1. Why Servlet Annotations?
  2. Types of Annotations
  3. @WebServlet Annotation with Example
  4. @WebInitParam Annotation with Example
  5. @WebFilter Annotation with Example
  6. @WebListener Annotation with Example
Why Servlet Annotations?

Servlet Annotations are introduced in Servlet API 2.5 (JEE 5.0, JSE 5.0). These annotations are used to avoid writing the web.xml file. The javax.servlet.annotation package contains a number of annotations that allow users to use annotations to declare servlets, filters, listeners, and specify the metadata for the declared component. The annotated classes will be processed by the Servlet Containers at the time of application deployment.

Types of Annotations
  1. HandlesTypes: It is used to declare the class types that a ServletContainerInitializer can handle.
  2. HttpConstraint: It is used within the ServletSecurity annotation to represent the security constraints to be applied to all HTTP protocol methods for which a corresponding HttpMethodConstraint element does NOT occur within the ServletSecurity annotation.
  3. HttpMethodConstraint: It is used within the ServletSecurity annotation to represent security constraints on specific HTTP protocol messages.
  4. MultipartConfig: It may be specified on a servlet class, indicating that instances of the Servlet except for requests that conform to the multipart/form-data MIME tags.
  5. ServletSecurity: It is used on a servlet implementation class to specify security constraints to be enforced by a Servlet container on HTTP protocol messages.
  6. WebFilter: It is used to declare a servlet filter.
  7. WebInitParam: It is used on a Servlet or Filter implementation class to specify an initialization parameter.
  8. WebServlet: It is used to declare a servlet.
  9. WebListener: It is used to declare a Web Listener.
@WebServlet Annotation

@WebServlet annotation is used to declare a Servlet. This annotation is processed by the container at deployment time and the corresponding servlet made available at the specified URL patterns.

Syntax:
@WebServlet(
       attribute1=value1,
       attribute2=value2,
       ……….
)
public class TheServlet extends javax.servlet.http.HttpServlet(
       //servlet code
}

Attributes of @WebServlet Annotation
  1. asyncSupported: It declares whether the servlet supports asynchronous operation mode.
  2. description: It gives the description of the servlet.
  3. displayName: It gives the display name of the servlet.
  4. initParams: It gives the init parameters of the servlet
  5. largeIcon: It gives the large-icon of the servlet
  6. loadOnStartup: It gives the load-on-startup order of the servlet
  7. name: It gives the name of the servlet.
  8. smallIcon: It gives the small-icon of the servlet.
  9. urlPatterns: It gives the URL patterns of the servlet.
  10. value: It gives the Array of URL patterns.
@WebServlet Annotation Example:

SimpleWebServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/SimpleWebServlet") 
public class SimpleWebServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    public 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>");
    }
}

Output

@WebServlet Annotation Example

@WebInitParam Annotation

@WebInitParam is used on a Servlet or Filter implementation class to specify an initialization parameter for a servlet or filter. It is used in conjunction with @WebServlet and @WebFilter annotations.

Syntax:
@WebInitParam(
        name = <name>,
        value = <value>,
        description = <value>
)

Attributes of @WebInitParam Annotation
  1. name: It gives the name of the parameter
  2. value: It gives the value of the parameter
  3. description: It gives the description of the parameter
@WebInitParam Annotation Example in Servlet

Simple.java

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>");
    }
}

Output

@WebInitParam Annotation Example in Servlet

@WebFilter Annotation

@WebFilter annotation is processed by the container at deployment time and the corresponding filter applied to the specified URL patterns, servlets, and dispatcher types.

Syntax:
@WebFilter(
       attribute1=value1,
       attribute2=value2,
        ………
)
public class Thefilter implements javax.servlet.Filter{
         //implements Filter’s methods : init(), doFilter() and destroy()
}

Attributes of @WebFilter Annotation
  1. asyncSupported: It declares whether the servlet supports asynchronous operation mode.
  2. description: It gives the description of the servlet.
  3. dispatcherTypes: It gives the dispatcher types to which the filter applies.
  4. displayName: It gives the display name of the servlet.
  5. filterName: It gives the name of the filter.
  6. initParams: It gives the init parameters of the servlet
  7. largeIcon: It gives the large-icon of the servlet.
  8. servletNames: It gives the name of the servlets to which the filter applies.
  9. smallIcon: It gives the small-icon of the servlet.
  10. urlPatterns: It gives the URL patterns of the servlet.
  11. value: It gives the Array of URL patterns.
@WebFilter Annotation Example in Servlet

LogFilter.java

import java.io.IOException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.*;
import java.util.*;

// Implements 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 init parameter
        String testParam = config.getInitParameter ("test-param");
        // Print the init parameter
        System.out.println ("Test Param: " + testParam);
    }

    public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    {
        // Log the current timestamp.
        System.out.println ("Time " + new Date ().toString ());
        // Pass request back down the filter chain
        chain.doFilter (request, response);
    }

    public void destroy ()
    {
        /*
        * Called before the Filter instance is removed from service by the web
        * container
        */
    }
}
Output

Run above Simple.java as usual where you will get the following output:

@WebFilter Annotation Example in Servlet

Now open your console, where you will get the following output with the value of testparam and current timestamp along with servlet notification.

Attributes of @WebFilter Annotation

@WebListener Annotation

@WebListener annotation is used to register a class as a listener of a web application. Any class annotated with WebListener must implemented one or more of the ServletContextListener, ServletContextAttributeListener, servletRequestListener, ServletRequestAttributeListener, HttpSessionListener, or HttpSessionAttributeListener interfaces.

Syntax:
@WebListener(
Attribute1 = value1,
Attribute2 = value2
……….
)
public class WebListenerExample implements HttpSessionListener, HttpSessionAttributeListener {
//code
}

Attributes of @WebListener Annotation
  1. value: It gives the description of the listener.
@WebListener Annotation Example in Servlet

ListenerTester.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet (name = "ListenerTester", urlPatterns = "/listener")
public class ListenerTester extends HttpServlet
{
    public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        PrintWriter out = response.getWriter ();
        HttpSession session = request.getSession ();
        out.println("<h3>This is a simple example of @WebServlet with @WebListener</h3>");
        session.setAttribute ("info", "My Info");
        String s = (String) session.getAttribute ("info");
        out.println ("<br>Attribute value that you have set = " + s);
        session.setAttribute ("info", "Your Info");
        String s1 = (String) session.getAttribute ("info");
        out.println ("<br>Attribute value has replaced by = " + s1);
        session.removeAttribute ("info");
        session.invalidate ();
    }

    public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doGet (request, response);
    }
}
WebListenerExample.java
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener()
public class WebListenerExample implements HttpSessionListener, HttpSessionAttributeListener
{
    public void sessionCreated (HttpSessionEvent he)
    {
        System.out.println ("Session is created");
    }

    public void sessionDestroyed (HttpSessionEvent he)
    {
        System.out.println ("Session is destroyed");
    }

    public void attributeAdded (HttpSessionBindingEvent arg0)
    {
        System.out.println ("value is added");
    }

    public void attributeRemoved (HttpSessionBindingEvent arg0)
    {
        System.out.println ("value is removed");
    }

    public void attributeReplaced (HttpSessionBindingEvent arg0)
    {
        System.out.println ("value has been replaced");
    }
}

web.xml

Here <listener></listener> entry is not required in web.xml file but in the older version, you were bound to map this entry into web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 <display-name>servletAnnotationExample</display-name>
 <listener>
  <listener-class>WebListenerExample</listener-class>
 </listener>
 <servlet>
  <servlet-name>ListenerTester</servlet-name>
  <servlet-class>ListenerTester</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>ListenerTester</servlet-name>
  <url-pattern>/listener</url-pattern>
 </servlet-mapping>
</web-app>
Output

Execute your code and you will get the following code.

@WebListener Annotation Example in Servlet

And on the console, you will get the following message

Servlet Annotations with Examples

In the next article, I am going to discuss the Servlet Input and Output Stream class. Here, in this article, I try to explain Servlet Annotations with Examples. I hope you enjoy this Servlet Annotations with Examples article.

Leave a Reply

Your email address will not be published.