@WebInitParam 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 @WebInitParam annotation to define initialization parameters for servlets. The @WebInitParam annotation is used within the @WebServlet annotation to provide configuration parameters to the servlet. This eliminates the need for configuration in the web.xml file.

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 @WebInitParam

Let's create a simple servlet that uses the @WebInitParam annotation to define initialization parameters.

UserInfoServlet.java

package net.javaguides.servlet.tutorial.httpservlet;

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;

/**
 * Create Servlet using @WebServlet and @WebInitParam annotations
 */
@WebServlet(
    urlPatterns = "/userinfo",
    initParams = {
        @WebInitParam(name = "firstName", value = "John"),
        @WebInitParam(name = "lastName", value = "Doe")
    }
)
public class UserInfoServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

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

        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();

        writer.println("<html><body>");
        writer.println("<h1>User Info Servlet</h1>");
        writer.println("<p>First Name: " + firstName + "</p>");
        writer.println("<p>Last Name: " + lastName + "</p>");
        writer.println("</body></html>");
    }
}

In this example, the UserInfoServlet is mapped to the URL pattern /userinfo. The @WebInitParam annotation is used to define two initialization parameters: firstName and lastName. These parameters are retrieved in the doGet method and displayed in the response.

Additional Examples of @WebInitParam

Multiple Initialization Parameters

You can define multiple initialization parameters using the @WebInitParam annotation.

@WebServlet(
    urlPatterns = "/userinfo",
    initParams = {
        @WebInitParam(name = "firstName", value = "John"),
        @WebInitParam(name = "lastName", value = "Doe"),
        @WebInitParam(name = "email", value = "john.doe@example.com")
    }
)
public class UserInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String firstName = getServletConfig().getInitParameter("firstName");
        String lastName = getServletConfig().getInitParameter("lastName");
        String email = getServletConfig().getInitParameter("email");

        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();

        writer.println("<html><body>");
        writer.println("<h1>User Info Servlet</h1>");
        writer.println("<p>First Name: " + firstName + "</p>");
        writer.println("<p>Last Name: " + lastName + "</p>");
        writer.println("<p>Email: " + email + "</p>");
        writer.println("</body></html>");
    }
}

Using @WebInitParam in a Complex Scenario

You can also use the @WebInitParam annotation in more complex scenarios involving multiple servlets or different initialization parameters for different URL patterns.

Conclusion

In this blog post, we demonstrated the usage of the @WebInitParam annotation to define initialization parameters for servlets. We covered the basic usage and provided additional examples to illustrate how to use multiple initialization parameters. The @WebInitParam annotation simplifies servlet configuration by allowing parameters to be defined directly in the servlet class.

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