@WebInitParam Annotation Example (Jakarta EE)

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 = "[email protected]")
    }
)
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

Comments