@WebServlet Annotation Example

In this article, we will discuss an important @WebServlet annotation with an example.
The @WebServlet annotation is used to define a Servlet component in a web application. This annotation is specified on a class and contains metadata about the Servlet being declared.
When we use @WebServlet annotation then deployment descriptor (web.xml file) is not required. While @WebServlet allows the mapping of servlets to occur in the Java code, the deployment descriptor file can still be used to map servlets.  In fact, there are still many valid reasons to have a web.xml file in your Web application.  Providing a list of welcome pages, defining error pages, and giving filters order are things that can only be done in the deployment descriptor.
Let's see a few important attributes of @WebServlet annotation and how to use it.

WebServlet Annotation Attributes

Below diagram shows a class diagram of @WebServlet annotation:
Let me list out all the attributes used to configure servlet using @WebServlet annotation:
  1. String name - Name of the Servlet
  2. String[] value - Array of URL patterns
  3. String[] urlPatterns - Array of URL patterns to which this Filter applies
  4. int loadOnStartup - The integer value gives you the startup ordering hint
  5. WebInitParam[] initParams - Array of initialization parameters for this Servlet
  6. Boolean asyncSupported - Asynchronous operation supported by this Servlet
  7. String smallIcon - Small icon for this Servlet, if present
  8. String largeIcon - Large icon for this Servlet, if present
  9. String description - Description of this Servlet, if present
  10. String displayName - Display name of this Servlet, if present
The urlPatterns or the value attribute on the annotation must be present. All other attributes are optional with default settings.

@WebServlet Annotation Example

Let's develop a complete example to demonstrate the usage of @WebServlet annotation. Classes annotated with @WebServlet class must extend the javax.servlet.http.HttpServlet class.

Step 1: Add servlet dependency to pom.xml

Let's first add servlet 4.0.1 dependency to our pom.xml:
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.servlet.tutorial</groupId>
    <artifactId>java-servlet-tutorial</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>java-servlet-tutorial Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>java-servlet-tutorial</finalName>
    </build>
</project>

Step 2: Create Servlet using @WebServlet Annotation

Following example demonstrates the usage of @WebServlet annotation:
package net.javaguides.servlet.tutorial.httpservlet;

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 = "/helloworld")
public class HelloWorldExample extends HttpServlet {

    private static final long serialVersionUID = 1 L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter printWriter = resp.getWriter();
        printWriter.print("<html>");
        printWriter.print("<body>");
        printWriter.print("<h1>Hello World HttpServlet Class Example</h1>");
        printWriter.print("<a href=\"http://www.javaguides.net\">Java Guides</a>");
        printWriter.print("</body>");
        printWriter.print("</html>");
        printWriter.close();
    }
}
Here the servlet HelloWorldExample is mapped to the URL pattern /helloworld. When accessing this servlet, it will display below page on the web browser: 
Let's see how to use @WebServlet annotation attributes with different scenarios.

A servlet is annotated with multiple URL patterns

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
 
@WebServlet(urlPatterns = {"/helloword", "/greeting"})
public class SampleUsingAnnotationAttributes extends HttpServlet {
    // implement servlet doPost() and doGet()...
}

Naming to servlet example

Let's use the name attribute to explicitly give a name to the servlet. In the below example, we are naming SampleUsingAnnotationAttributes servlet to "MyServlet".
@WebServlet(name =MyServlet”, urlPatterns = {
    "/foo",
    "/bar"
})
public class SampleUsingAnnotationAttributes extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) {}
}

Add description to the servlet

Let's use a description attribute to describe the given servlet:
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
 
@WebServlet(
        name = "MyOwnServlet",
        description = "Describe Servlet",
        urlPatterns = "/helloword"
)
public class HelloWorldServlet extends HttpServlet {
    // implement servlet doPost() and doGet()...
}

Declare a servlet with some init parameters

package net.javaguides.servlet.tutorial.httpservlet;

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;

/**
 * Create Servlet using @WebServlet annotation
 * @author Ramesh Fadatare
 *
 */
@WebServlet(
    urlPatterns = "/userinfo",
    initParams = {
        @WebInitParam(name = "firstName", value = "Ramesh"),
        @WebInitParam(name = "lastName", value = "Ramesh")
    }
)
public class HttpServletExample extends HttpServlet {

    private static final long serialVersionUID = 1 L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String firstName = getInitParameter("firstName");
        String lastName = getInitParameter("lastName");

        PrintWriter writer = resp.getWriter();

        writer.println("firstName = " + firstName);
        writer.println("lastName = " + lastName);
    }
}

Servlet with asynchronous operation mode and load-on-startup order example

package net.javaguides.servlet.tutorial.httpservlet;

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 = "/helloworld",
    loadOnStartup = 1,
    asyncSupported = true
)
public class HttpServletExample extends HttpServlet {

    private static final long serialVersionUID = 1 L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter printWriter = resp.getWriter();
        printWriter.print("<html>");
        printWriter.print("<body>");
        printWriter.print("<h1>Hello World HttpServlet Class Example</h1>");
        printWriter.print("<a href=\"http://www.javaguides.net\">Java Guides</a>");
        printWriter.print("</body>");
        printWriter.print("</html>");
        printWriter.close();
    }
}

Related Servlet Examples

Check out complete Servlet 4 tutorial at Servlet Tutorial

 Reference


Comments