How do I share data between servlets using ServletContext?

In Java Servlets, you can share data between servlets using the ServletContext object. The ServletContext is an application-wide object that all servlets in a web application can access. It allows servlets to share information. Here’s how you can use it:


Steps to Share Data Using ServletContext:

  1. Set Attribute in ServletContext:
    • A servlet can store an object in the ServletContext as an attribute using the setAttribute method.
    ServletContext context = getServletContext();
    context.setAttribute("sharedData", "This is shared data");
    
  2. Retrieve the Attribute in Another Servlet:
    • Another servlet can retrieve the shared data using the getAttribute method.
    ServletContext context = getServletContext();
    String sharedData = (String) context.getAttribute("sharedData");
    
  3. (Optional) Remove the Attribute:
    • If needed, you can remove the attribute using the removeAttribute method.
    context.removeAttribute("sharedData");
    

Example Use Case:

Create two servlets: one for setting the data and one for retrieving it.

SetDataServlet.java

package org.kodejava.servlet;

import jakarta.servlet.ServletContext;
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;

@WebServlet("/setData")
public class SetDataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set shared data in ServletContext
        ServletContext context = getServletContext();
        context.setAttribute("sharedData", "Hello from SetDataServlet!");

        response.getWriter().println("Data set successfully.");
    }
}

GetDataServlet.java

package org.kodejava.servlet;

import jakarta.servlet.ServletContext;
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;

@WebServlet("/getData")
public class GetDataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Retrieve shared data from ServletContext
        ServletContext context = getServletContext();
        String sharedData = (String) context.getAttribute("sharedData");

        response.getWriter().println("Shared Data: " + sharedData);
    }
}

Key Points:

  1. Application Scope:
    • Attributes in the ServletContext are available globally across the web application. They can be accessed by all servlets and JSPs.
  2. Thread-Safety:
    • Be cautious about thread safety because servlets handle multiple requests concurrently. If multiple threads modify the shared data simultaneously, data consistency issues may occur.
    • You may need to synchronize access to the shared object.
  3. Lifecycle:
    • Attributes in the ServletContext remain in memory until they are explicitly removed using removeAttribute, or the application is redeployed/stopped.

Advanced Sharing via ServletContextListener:

If you need to initialize or clean up shared data when the application starts or stops, you can use a ServletContextListener.

package org.kodejava.servlet;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        context.setAttribute("sharedData", "Initial shared data");
        System.out.println("Application started. Shared data set.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Application stopped. Cleaning up...");
    }
}

This ensures shared data is set and removed in a centralized manner.


This approach to sharing data is straightforward and works seamlessly for many use cases in a web application.

Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central

How to Install and Set Up Java 17 on Your System

To install and set up Java 17 on your system, follow the steps below. The process may vary slightly depending on your operating system.


On Windows

  1. Download Java 17
  2. Install Java 17
    • Run the .msi installer file and follow the setup instructions.
    • Install Java in the default directory or specify a custom directory (e.g., C:\Program Files\Java\jdk-17).
  3. Set Environment Variables
    • Open the Start menu, search for “Environment Variables,” and click on “Edit the system environment variables.”
    • In the System Properties window, click on the “Environment Variables” button.
    • Under “System Variables,” find the Path variable and click Edit.
    • Add the path to the bin directory of your Java installation (e.g., C:\Program Files\Java\jdk-17\bin).
    • Click OK on all windows to save your changes.
    • Optionally, set a JAVA_HOME variable:
      • Click New under “System Variables.”
      • Name the variable JAVA_HOME and set its value to the path of your Java installation (e.g., C:\Program Files\Java\jdk-17).
  4. Verify Installation
    • Open a Command Prompt and run:
    java -version
    
    • If installed properly, it will display the Java 17 version.

On macOS

  1. Download Java 17
    • Visit the Oracle JDK or OpenJDK website, and download the .dmg installer for macOS.
  2. Install Java 17
    • Open the .dmg file and follow the installation instructions.
    • Java will be installed, usually in /Library/Java/JavaVirtualMachines/.
  3. Set Environment Variables (Optional)
    • Open a terminal and edit the ~/.zshrc (for zsh users) or ~/.bash_profile (for bash users) file using a text editor.
    • Add the following lines to set the JAVA_HOME variable:
    export JAVA_HOME=$(/usr/libexec/java_home -v 17)
    export PATH=$JAVA_HOME/bin:$PATH
    
    • Save and close the file, then reload the shell configuration:
    source ~/.zshrc
    
    • Note: The /usr/libexec/java_home command automatically detects installed Java versions.
  4. Verify Installation
    • Run the following in Terminal:
    java -version
    
    • It should show the Java 17 version.

On Linux

  1. Install OpenJDK 17
    • Use your package manager to install OpenJDK 17:
      • For Debian/Ubuntu-based systems:
      sudo apt update
      sudo apt install openjdk-17-jdk
      
      • For Red Hat/CentOS/Fedora-based systems:
      sudo dnf install java-17-openjdk-devel
      
  2. Set Default Java Version
    • If multiple Java versions are installed, you can set Java 17 as the default:
    sudo update-alternatives --config java
    
    • Select the path for Java 17 from the list.
  3. Set Environment Variables
    • Edit the ~/.bashrc or ~/.zshrc file and add:
    export JAVA_HOME=/usr/lib/jvm/java-17-openjdk
    export PATH=$JAVA_HOME/bin:$PATH
    
    • Save the file and reload it:
    source ~/.bashrc
    
  4. Verify Installation
    • Run the following command:
    java -version
    
    • It should display details about Java 17.

Optional: Verify Java Compiler

To ensure the javac compiler is working:

javac -version

That’s it! Now Java 17 is installed and ready to use.

How do I initialize servlet parameters with ServletConfig?

You can initialize servlet parameters in a Java Servlet by using the ServletConfig object. The ServletConfig object contains initialization parameters and configuration data for a specific servlet. These parameters are specified in the web application’s deployment descriptor (web.xml file).

Here’s a step-by-step guide to using ServletConfig for initializing servlet parameters:


1. Define Initialization Parameters in web.xml

Define the initialization parameters for the servlet in the web.xml deployment descriptor using the <init-param> element inside the <servlet> element.

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" version="10">
    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>org.kodejava.servlet.MyServlet</servlet-class>
        <init-param>
            <param-name>param1</param-name>
            <param-value>value1</param-value>
        </init-param>
        <init-param>
            <param-name>param2</param-name>
            <param-value>value2</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/myServlet</url-pattern>
    </servlet-mapping>
</web-app>

2. Implement the Servlet and Use ServletConfig

The servlet can retrieve these initialization parameters using the ServletConfig object. Typically, you retrieve ServletConfig in the init() method of the servlet.

Here’s an example:

package org.kodejava.servlet;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class MyServletConfig extends HttpServlet {

    private String param1;
    private String param2;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        // Retrieve initialization parameters from ServletConfig
        param1 = config.getInitParameter("param1");
        param2 = config.getInitParameter("param2");

        // Log values (optional)
        System.out.println("Parameter 1: " + param1);
        System.out.println("Parameter 2: " + param2);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Use the initialized parameters
        resp.setContentType("text/plain");
        resp.getWriter().write("Param1: " + param1 + "\nParam2: " + param2);
    }
}

3. Access Parameters from ServletConfig

  • ServletConfig.getInitParameter(String name): Retrieves a single initialization parameter by its name.
  • ServletConfig.getInitParameterNames(): Returns an Enumeration of all defined parameter names.

For example:

Enumeration<String> parameterNames = config.getInitParameterNames();
while (parameterNames.hasMoreElements()) {
    String paramName = parameterNames.nextElement();
    System.out.println("Parameter Name: " + paramName + ", Value: " + config.getInitParameter(paramName));
}

Output

When you access the servlet (/myServlet), the servlet will use the parameters specified in the web.xml file and display:

Param1: value1
Param2: value2

This is how you can initialize servlet parameters using ServletConfig. It allows you to externalize configuration values, making them easier to modify without changing the servlet code.

Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central

How do I create a servlet filter using Filter and FilterChain?

Creating a servlet filter using the Filter interface and FilterChain is straightforward in Jakarta EE (or Java EE). A filter is used to perform filtering tasks like logging, authentication, authorization, etc., on requests or responses. Here’s how you can create a servlet filter step by step:

Steps to Create a Servlet Filter

  1. Implement the Filter interface:
    • The Filter interface provides three methods to override: init(), doFilter(), and destroy().
  2. Configure the filter:
    • Filters can be configured either programmatically (via annotations) or declaratively (via web.xml).

1. Code Example of a Filter Implementation

package org.kodejava.servlet;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;

import java.io.IOException;

// Use @WebFilter annotation to map the filter to a URL pattern
@WebFilter(urlPatterns = "/*") // This applies the filter to all URLs
public class MyServletFilter implements Filter {

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
      // Initialization logic (called once when the filter is first loaded)
      System.out.println("Initializing MyServletFilter...");
   }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
           throws IOException, ServletException {
      // Logic before passing request to the next filter or servlet
      System.out.println("Request intercepted by MyServletFilter!");

      // Pass the request/response to the next filter or the target servlet
      chain.doFilter(request, response);

      // Logic after the request is processed by the servlet/next filter
      System.out.println("Response processed by MyServletFilter!");
   }

   @Override
   public void destroy() {
      // Cleanup logic (called once when the filter is taken out of service)
      System.out.println("Destroying MyServletFilter...");
   }
}

2. Explanation of Methods in the Filter Interface

  1. init(FilterConfig filterConfig):
    • Called once when the filter is initialized.
    • Use this method for any one-time setup or resource allocation.
  2. doFilter(ServletRequest request, ServletResponse response, FilterChain chain):
    • The core method where the filtering logic is applied.
    • You can manipulate the request before calling chain.doFilter() to pass it along the filter chain or the servlet.
    • After chain.doFilter(), you can manipulate the response as needed.
  3. destroy():
    • This method is called once when the filter is being taken out of service (e.g., when the application is shutting down).
    • Use this for cleaning up resources (closing connections, releasing memory, etc.).

3. Configure the Filter in web.xml (Optional)

Instead of using the @WebFilter annotation, you can configure your filter in the web.xml file.

<filter>
    <filter-name>MyServletFilter</filter-name>
    <filter-class>com.example.MyServletFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyServletFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

4. How Filters Work in the Chain

  • Filters in the chain are invoked in the order they are mapped.
  • The doFilter() method ensures proper chaining of requests/responses by calling chain.doFilter() to pass the request to the next filter or servlet.
  • If you skip chain.doFilter(), the request won’t proceed further.

Example Workflow

  1. Before calling chain.doFilter():
    • You can add custom logic, such as logging the request or checking for specific headers, parameters, or cookies.
  2. After chain.doFilter():
    • You can modify the response, such as adding HTTP headers, statistics, etc.

Request flow for the above filter:

  1. A client sends a request.
  2. The filter intercepts the request.
  3. Pre-processing (before calling chain.doFilter()).
  4. Request is passed to the servlet or next filter (via chain.doFilter()).
  5. Post-processing (after chain.doFilter()).
  6. The client receives the response.

This is how servlet filters can be implemented to intercept and process requests and responses in Jakarta EE.


Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central

How do I use annotations to define Jakarta Servlet?

In Jakarta EE, you can define servlets using annotations instead of the traditional web.xml deployment descriptor. The most common annotation used for this purpose is @WebServlet. Here’s an overview of how to use annotations to define servlets:

1. Basic Syntax of the @WebServlet Annotation

The @WebServlet annotation is used to declare a servlet and map it to a URL pattern. It belongs to the jakarta.servlet.annotation package.

package org.kodejava.servlet;

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;

@WebServlet(name = "MyServlet", urlPatterns = {"/hello", "/greet"})
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<h1>Hello, World!</h1>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<h1>Post Request Handled</h1>");
    }
}

2. Parameters of @WebServlet

The @WebServlet annotation has several attributes you can set:

  1. name: Specifies the name of the servlet. This is optional.
  2. urlPatterns (or value): An array of URL patterns to which the servlet will respond. The urlPatterns or value element is required.
  3. loadOnStartup: Specifies the servlet’s load-on-startup priority. If set to a positive integer, the servlet will be loaded and initialized during deployment, not upon its first request.
  4. asyncSupported: A boolean indicating whether the servlet supports asynchronous processing. Default is false.

Example with Additional Attributes

package org.kodejava.servlet;

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;

@WebServlet(
        name = "ExampleServlet",
        urlPatterns = "/example",
        loadOnStartup = 1,
        asyncSupported = true
)
public class ExampleServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain");
        response.getWriter().println("Welcome to the Example Servlet!");
    }
}

3. How It Works

  • No web.xml Needed: When you use @WebServlet, there’s no need to register the servlet manually in web.xml. The application server automatically registers the servlet based on the annotation configuration.
  • URL Patterns: You define the URLs (using urlPatterns or value) to which the servlet will respond.

4. Multiple URL Patterns

You can map multiple URL patterns to the same servlet using an array:

package org.kodejava.servlet;

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;

@WebServlet(urlPatterns = {"/path1", "/path2", "/path3"})
public class MultiPathServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain");
        response.getWriter().println("This servlet can handle multiple paths!");
    }
}

5. Use with Filters and Listeners

Annotations can also be used for filters (@WebFilter) and listeners (@WebListener). For example:

  • @WebFilter for filters
  • @WebListener for event listeners

Conclusion

Using annotations to define servlets makes your code more concise and simplifies configuration. It eliminates the need for verbose web.xml entries and is easier to maintain, particularly in modern Jakarta EE-based applications.


Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central