@WebServlet Annotation Example (Jakarta EE)

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

In this blog post, we'll explore the usage of the @WebServlet annotation from the jakarta.servlet package to create and configure servlets in Java. The @WebServlet annotation simplifies the process of servlet declaration and configuration, eliminating the need for web.xml entries. We will demonstrate a complete example using the latest Jakarta Servlet dependency.

Step 1: Add Servlet Dependency to pom.xml

First, we need to add the Jakarta Servlet dependency to our pom.xml file. Here, we are using version 6.1.0.

<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>
        <!-- Jakarta Servlet dependency -->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>java-servlet-tutorial</finalName>
    </build>
</project>

Step 2: Create a Servlet Using @WebServlet Annotation

Now, let's create a simple servlet using the @WebServlet annotation.

HelloWorldExample.java

package net.javaguides.servlet.tutorial.httpservlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/helloworld")
public class HelloWorldExample extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @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();
    }
}

In this example, the servlet HelloWorldExample is mapped to the URL pattern /helloworld. When accessed, it displays a simple HTML page.

Commonly Used @WebServlet Annotation Attributes

The @WebServlet annotation comes with several attributes that allow for fine-grained configuration of servlets. Here are some commonly used attributes:

  • urlPatterns or value: Defines the URL patterns to which the servlet responds.
  • name: Provides a name for the servlet.
  • description: Adds a description to the servlet.
  • initParams: Specifies initialization parameters for the servlet.
  • loadOnStartup: Determines the load order of the servlet.
  • asyncSupported: Indicates whether the servlet supports asynchronous processing.

For a complete list of attributes, refer to the official Jakarta Servlet API documentation.

Additional @WebServlet Annotation Examples

Multiple URL Patterns

A servlet can be mapped to multiple URL patterns.

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;

@WebServlet(urlPatterns = {"/helloworld", "/greeting"})
public class SampleUsingAnnotationAttributes extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Handle the request
    }
}

Naming the Servlet

The name attribute can be used to give the servlet an explicit name.

@WebServlet(name = "MyServlet", urlPatterns = {"/foo", "/bar"})
public class SampleUsingAnnotationAttributes extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Handle the request
    }
}

Adding a Description

The description attribute can be used to describe the servlet.

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;

@WebServlet(
        name = "MyOwnServlet",
        description = "Describe Servlet",
        urlPatterns = "/helloworld"
)
public class HelloWorldServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Handle the request
    }
}

Init Parameters

Init parameters can be defined using the initParams attribute.

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

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

    private static final long serialVersionUID = 1L;

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

Asynchronous Operation and Load-on-Startup

You can configure the servlet for asynchronous operation and specify the load-on-startup order.

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(
    urlPatterns = "/helloworld",
    loadOnStartup = 1,
    asyncSupported = true
)
public class HttpServletExample extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @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();
    }
}

Conclusion

In this blog post, we demonstrated the usage of the @WebServlet annotation to create and configure servlets in Java. We covered various attributes of the @WebServlet annotation, including urlPatterns, name, description, initParams, loadOnStartup, and asyncSupported. Using annotations simplifies servlet development by eliminating the need for web.xml configuration.

References

Related Servlet Posts

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare