Servlet with Annotation

Last Updated : 8 May, 2026

Servlet annotations provide an easier way to configure servlets without using the web.xml deployment descriptor file. Using annotations, URL mappings and servlet configurations can be defined directly inside the servlet class, making the application simpler and easier to manage.

  • Configure servlets directly using annotations like @WebServlet.
  • Eliminate the need for manual servlet mapping in web.xml.
  • Simplify request handling and servlet configuration in web applications.

Configuration using annotation:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
// Code to be executed...
}

Configuration using web.xml file:

<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

Types of Annotations Used in Servlet

Following are the types of annotation used in Servlet.

1. @WebServlet

  • it is used to define and configure a servlet directly in the Java class.
  • Maps client requests to a servlet class.
  • Eliminates the need for servlet configuration in web.xml.
  • Simplifies servlet URL mapping and management.

Syntax:

@WebServlet("/demo")
public class DemoServlet extends HttpServlet {
}

Elements of @WebServlet Annotation

Name

Modifier and Type

Description

Default value

asyncSupportedbooleanTo specify whether the servlet supports asynchronous mode or not.false
descriptionStringTo provide a description of the servlet.""
displayNameStringTo provide the Display name of the Servlet.""
initParamsWebInitParam[]To specify initialization parameters of the servlet.{}
nameStringTo provide the name of the servlet.""
valueString[]To specify the URL pattern of the servlet that is to be mapped.{}
urlPatternsString[]To provide the URL patterns of the servlet that are to be mapped.{}
smallIconStringTo specify the small icon name of the servlet.""
loadOnStartupintTo provide the load on the startup order of the servlet.-1
largeIconStringTo specify the large icon name of the servlet.""

2. @WebFilter

  • it is used to create filters for request and response processing.
  • Intercepts client requests before reaching the servlet.
  • Performs tasks like authentication and logging.
  • Can modify requests and responses dynamically.

Syntax:

@WebFilter("/demo")
public class DemoFilter implements Filter {
}

3. @WebListener

  • it is used to create listeners for handling application, session, or request events.
  • Listens to application lifecycle events.
  • Handles session and request-related events.
  • Used for initialization and resource management.

Syntax:

@WebListener
public class DemoListener implements ServletContextListener {
}

Different Example With Servlet Annotation for better understanding

Here below we discuss multiple example tp Explore Servlet annotation with different ways.

Example 1: Servlet annotated with only URL pattern

For better understanding, we will create a simple HTML page to map the Servlet with the URL.

index.html

HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home</title>
</head>
<body>
    <form action="hello" method="post">

        Welcome Page: <input type="submit" />

    </form>
</body>
</html>

Html page which maps the servlet with URL "/hello".

HelloServlet.java

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

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {

        // set the response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Print hello message to the client browser in
        // response object
        out.println(
            "<h3>Hello, Welcome to GeeksforGeeks!!</h3>");
        out.close();
    }
}
  • When the user clicks Submit, the container maps the request using @WebServlet("/hello").
  • Since the form method is POST, the container executes the doPost() method of HelloServlet.

Output:

  • Run the project on the server to get the output.
  • URL: http://localhost:8081/ServletFlow/index.html
index.html file
  • Click on Submit.
Welcome Page

We can see the URL mapping to the "HelloServlet" class and the output.

Example 2: Servlet annotated with servlet information

HelloServlet.java

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(name = "Hello Servlet",
            displayName = "Annotated Hello Servlet",
            description
            = "This is annotated servlet example.",
            value = "/hello")
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {

        // set the response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Print hello message to the client browser in
        // response object
        out.println(
            "<h3>Hello, Welcome to GeeksforGeeks!!</h3>");
        out.println(
            "<h4>Annotated servlet with elements - name, displayName, description and value</h4>");
        out.close();
    }
}
  • Annotated elements can define the servlet name and description.
  • URL mapping can be configured using the value element.

Output:

  • Run the project and click on submit.
Welcome Page

Example 3: Servlet annotated with Initialization parameters

HelloServlet.java

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 = "/hello",
    initParams
    = { @WebInitParam(name = "name", value = "Geek")
        , })
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {

        // Get the initialized parameter value
        String name = getInitParameter("name");

        // set the response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Print hello message to the client browser in
        // response object
        out.println("<h3>Hello " + name
                    + ", Welcome to GeeksforGeeks!!</h3>");
        out.println(
            "<h4>Annotated servlet with Initialization parameter.</h4>");
        out.close();
    }
}
  • @WebInitParam is used to initialize servlet parameters.
  • The container processes these parameters during servlet initialization.
  • Here, the parameter name is initialized with the value Geek.

Output:

  • Run the project and click on submit.
Welcome Page

Example 4: Servlet annotated with load-on-start up value and asynchronous support

HelloServlet.java

Java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
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(value = "/hello", loadOnStartup = 1,
            asyncSupported = true)
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void init(ServletConfig config)
    {
        System.out.println(
            "Hello Servlet has been initialized");
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {

        // set the response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Print hello message to the client browser in
        // response object
        out.println(
            "<h3>Hello, Welcome to GeeksforGeeks!!</h3>");
        out.println(
            "<h4>Annotated servlet with load-on-start up value and asynchronous support.</h4>");
        out.close();
    }
}
  • By default, the servlet is loaded when the first client request arrives.
  • Using loadOnStartup = 1 loads and initializes the servlet during server startup.
  • Setting asyncSupported = true enables asynchronous processing support.

Output:

  • Run the project on the server.
  • We can see the servlet is loaded, instantiated(init() method) and Initialized at the time of servlet deployment into the server.
Output
  • The initialization message appears in the console during server startup, and the servlet response is displayed in the browser.
Welcome Page

Example 5: Servlet annotated with multiple URL patterns

index.html

HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home</title>
</head>
<body>
    <form action="hello" method="post">
        Click here for Welcome Page(using /hello URL): <input type="submit" />
    </form>
    <form action="welcome" method="get">
        Click here for Welcome Page(using /welcome URL): <input type="submit" />
    </form>
</body>
</html>

HelloServlet.java

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(urlPatterns = { "/welcome", "/hello" })
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {

        // set the response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Print hello message to the client browser in
        // response object
        out.println(
            "<h3>Hello, Welcome to GeeksforGeeks!!</h3>");
        out.println(
            "<h4>Annotated servlet with multiple URLs inside Get method.</h4>");
        out.close();
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {

        // set the response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Print hello message to the client browser in
        // response object
        out.println(
            "<h3>Hello, Welcome to GeeksforGeeks!!</h3>");
        out.println(
            "<h4>Annotated servlet with multiple URLs inside Post method.</h4>");
        out.close();
    }
}
  • Requests for /hello and /welcome are mapped to the same servlet, where /hello executes doPost() and /welcome executes doGet().

Output:

  • Run the project.
index.html
  • When click on "/hello" submit button, container will execute "doPost()" method in the "HelloServlet" and below output will be generated with that URL.
Welcome page - Post method
  • When click on "/welcome" submit button, container will execute "doGet()" method in the "HelloServlet" and below output will be generated with that URL.
Welcome page - Get method

Note: The container maps both /hello and /welcome requests to HelloServlet and generates the corresponding response.

Comment