<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ahmed Jaad</title>
    <description>The latest articles on DEV Community by Ahmed Jaad (@ahmedjaad).</description>
    <link>https://dev.to/ahmedjaad</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F377351%2Fab21c59f-ecb6-489a-8630-eda766c9f9fd.JPG</url>
      <title>DEV Community: Ahmed Jaad</title>
      <link>https://dev.to/ahmedjaad</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ahmedjaad"/>
    <language>en</language>
    <item>
      <title>Designing and Implementing an API Rate Limiter</title>
      <dc:creator>Ahmed Jaad</dc:creator>
      <pubDate>Sun, 19 Jan 2025 22:52:55 +0000</pubDate>
      <link>https://dev.to/ahmedjaad/designing-and-implementing-an-api-rate-limiter-1f9m</link>
      <guid>https://dev.to/ahmedjaad/designing-and-implementing-an-api-rate-limiter-1f9m</guid>
      <description>&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The implementation is available on &lt;a href="https://github.com/ahmedjaadi/api-rate-limiter" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Introduction&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Understanding the Architecture of an API Rate Limiter&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;What is Throttling?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Client Responsibilities&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Designing the Application&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Introduction&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;APIs serve as the backbone of modern software systems, enabling communication between different applications. However, without proper control, APIs can be overwhelmed by excessive requests, potentially leading to degraded performance or even downtime. This is where API rate limiting comes into play.&lt;/p&gt;

&lt;p&gt;API rate limiting is a mechanism that restricts the number of requests a client can make to an API within a specified time period. By doing so, it ensures fair usage among clients, protects system resources, and maintains service stability. In this article, we will first explore important concepts(components) relevant to API rate limiting, and then we see the design and implementation of an API rate limiter using the Spring framework and Redis. The full implementation code is available on &lt;a href="https://github.com/ahmedjaadi/api-rate-limiter" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Should You Rate Limit Your API?
&lt;/h2&gt;

&lt;p&gt;APIs are integral to many businesses, and their reliability is critical. Implementing a rate limiter provides several benefits:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Enhancing Security&lt;/strong&gt;: Rate limiting prevents denial-of-service (DoS) attacks by limiting the number of requests a malicious user can make.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mitigating Noisy Neighbors&lt;/strong&gt;: In multi-tenant systems, one client’s excessive use should not degrade the performance experienced by others.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Preventing Resource Starvation&lt;/strong&gt;: Rate limiting ensures that API consumers cannot monopolize resources, safeguarding the infrastructure from being overwhelmed.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Understanding the Architecture of an API Rate Limiter
&lt;/h2&gt;

&lt;p&gt;A robust API rate limiter consists of several key components working together to manage and enforce rate limits. Let’s delve into the architecture:&lt;/p&gt;

&lt;h3&gt;
  
  
  Load Balancer
&lt;/h3&gt;

&lt;p&gt;A load balancer is a standard component in distributed systems. It evenly distributes incoming network traffic across multiple service instances to ensure reliability and scalability. In the context of rate limiting, it ensures that no single instance of the rate limiter or the protected API server is overwhelmed.&lt;/p&gt;

&lt;h3&gt;
  
  
  Rate Limiter
&lt;/h3&gt;

&lt;p&gt;The rate limiter is the core component. It intercepts requests before they reach the protected API server (often called the Request Processor). Based on predefined rules, the rate limiter decides whether to allow or throttle requests. Throttling may involve rejecting requests or queuing them for later processing.&lt;/p&gt;

&lt;h3&gt;
  
  
  Request Processor
&lt;/h3&gt;

&lt;p&gt;This is the actual API server that processes valid requests. In our prototype, the rate limiter and the request processor are combined for simplicity. However, in real-world scenarios, these are often separate applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  Redis as a Distributed Cache
&lt;/h3&gt;

&lt;p&gt;Redis is used to store and sync rate limit states across distributed instances of the rate limiter. It ensures that all instances share a consistent view of the rate limits, making the system scalable and fault-tolerant.&lt;/p&gt;

&lt;h3&gt;
  
  
  Rules Engine Service and Database
&lt;/h3&gt;

&lt;p&gt;The rules engine service defines the rate-limiting policies, such as the maximum number of requests allowed per time window and the actions to take when limits are exceeded. For brevity, our prototype uses hardcoded rules, but in a production-grade system, these rules would be dynamically retrieved from a database.&lt;/p&gt;

&lt;h3&gt;
  
  
  Queue
&lt;/h3&gt;

&lt;p&gt;A queue can serve multiple purposes, such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Temporarily holding requests during high traffic periods for later processing.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Implementing soft throttling by delaying requests instead of outright rejecting them.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fgithub.com%2Fahmedjaadi%2Fapi-rate-limiter%2Fblob%2Fc85ffd2ada37bb153ae23d7b4019bb83a5e22957%2Fdocs%2Fhigh_level_architecture.png%3Fraw%3Dtrue" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fgithub.com%2Fahmedjaadi%2Fapi-rate-limiter%2Fblob%2Fc85ffd2ada37bb153ae23d7b4019bb83a5e22957%2Fdocs%2Fhigh_level_architecture.png%3Fraw%3Dtrue" alt="high level architecture" width="4838" height="2631"&gt;&lt;/a&gt;&lt;/p&gt;
High-Level Architecture



&lt;h2&gt;
  
  
  What is Scaling and How Is It Implemented?
&lt;/h2&gt;

&lt;p&gt;Scaling refers to the ability of a system to handle increasing amounts of workload by adding resources. In the context of an API rate limiter, scaling ensures that the system can manage growing traffic without performance degradation. There are two types of scaling:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Vertical Scaling&lt;/strong&gt;: Adding more resources (e.g., CPU, memory) to a single instance. While straightforward, it has physical limits and can become costly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Horizontal Scaling&lt;/strong&gt;: Adding more instances of a service to distribute the workload. This is the preferred approach for modern distributed systems as it offers better resilience and flexibility.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In our implementation, horizontal scaling is achieved by:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Deploying multiple instances of the rate limiter, each paired with a request processor.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using Redis as a distributed cache to synchronize rate limit states across all instances.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fgithub.com%2Fahmedjaadi%2Fapi-rate-limiter%2Fblob%2Fc85ffd2ada37bb153ae23d7b4019bb83a5e22957%2Fdocs%2Fscaling.png%3Fraw%3Dtrue" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fgithub.com%2Fahmedjaadi%2Fapi-rate-limiter%2Fblob%2Fc85ffd2ada37bb153ae23d7b4019bb83a5e22957%2Fdocs%2Fscaling.png%3Fraw%3Dtrue" alt="scaling" width="760" height="452"&gt;&lt;/a&gt;&lt;/p&gt;
Scaling



&lt;h2&gt;
  
  
  What is Throttling?
&lt;/h2&gt;

&lt;p&gt;Throttling is the process of regulating the rate of incoming requests to an API. When a client exceeds its allowed quota, throttling mechanisms decide how to handle the excess requests. There are two main strategies:&lt;/p&gt;

&lt;h3&gt;
  
  
  Hard Throttling
&lt;/h3&gt;

&lt;p&gt;Hard throttling enforces strict limits. Once a client reaches its quota, any additional requests are immediately rejected. This approach is straightforward and is typically applied to general or untrusted clients.&lt;/p&gt;

&lt;h3&gt;
  
  
  Soft Throttling
&lt;/h3&gt;

&lt;p&gt;Soft throttling provides a more lenient approach, especially for premium or trusted clients. Instead of outright rejecting requests, soft throttling may:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Allow a certain percentage of excess requests to pass through.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Queue excess requests for processing once traffic subsides.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The choice between hard and soft throttling depends on business requirements. For instance, a subscription-based service might implement soft throttling for premium users to enhance their experience, while applying hard throttling for standard users.&lt;/p&gt;

&lt;h2&gt;
  
  
  Client Responsibilities
&lt;/h2&gt;

&lt;p&gt;To ensure the effectiveness of the rate limiter, clients should adopt best practices:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Exponential Backoff&lt;/strong&gt;: Retry requests after progressively longer delays when encountering failures. This reduces server load and avoids immediate retries.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Jitter&lt;/strong&gt;: Add random delays (Jitter) to retry intervals to prevent simultaneous retries from multiple clients, which can overwhelm the server.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Designing the Application
&lt;/h2&gt;

&lt;h3&gt;
  
  
  High-Level Architecture
&lt;/h3&gt;

&lt;p&gt;Our application’s architecture is simplified for clarity and practicality, with some components removed or merged:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;strong&gt;RateLimiter&lt;/strong&gt; (under the &lt;strong&gt;api_rate_limiter&lt;/strong&gt; package) and &lt;strong&gt;RequestProcessor&lt;/strong&gt; (under the &lt;strong&gt;request_processor&lt;/strong&gt; package) are combined into a single Spring Boot application. In real-world scenarios, these two components might exist as separate applications.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The application does not include a &lt;strong&gt;Load Balancer&lt;/strong&gt; or a &lt;strong&gt;Queue&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Rules&lt;/strong&gt; are hard-coded, eliminating the need for a &lt;strong&gt;Rules Service&lt;/strong&gt; and a &lt;strong&gt;Rules Engine&lt;/strong&gt; Database.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Distributed caching is supported using &lt;strong&gt;Redis&lt;/strong&gt;. However, for scenarios where &lt;strong&gt;Redis&lt;/strong&gt; is unavailable, an alternative approach is provided with a standalone runtime profile, where rules are stored in the application’s memory.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All applicable rules, including system-wide and tenant-specific rules, are applied dynamically. This ensures fair and precise enforcement of rate limits for every tenant.&lt;/p&gt;

&lt;h3&gt;
  
  
  Domain Modeling
&lt;/h3&gt;

&lt;p&gt;The application revolves around a few core domain entities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;RateLimit&lt;/strong&gt;: Defines the properties of a rate limit, such as capacity and time period.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;TenantRateLimit&lt;/strong&gt;: Represents the rate limits applicable to a specific tenant. It includes properties for monthly and time-window limits.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Bucket&lt;/strong&gt;: Tracks the live state of rate limits for each tenant. There is also a system-wide bucket for global limits.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0l6p394yhuww6x41k94o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0l6p394yhuww6x41k94o.png" alt="domain model" width="648" height="311"&gt;&lt;/a&gt;&lt;/p&gt;
Domain Model



&lt;h3&gt;
  
  
  Service Interactions
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;TenantBucketProvider&lt;/strong&gt;: This is the actual service that the &lt;strong&gt;Rate Limiter&lt;/strong&gt; relies on to make the decision whether to let a request through or not. Manages the limit states for tenants. It has two implementations:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;StandaloneBucketProvider&lt;/strong&gt;: Uses in-memory storage, suitable for standalone applications but not scalable.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;RedisBucketProvider&lt;/strong&gt;: Uses Redis for distributed environments, enabling horizontal scalability.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;ApiServerSender&lt;/strong&gt;: Forwards valid requests to the protected API server.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqxl82zwkdfwr13cnlkvq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqxl82zwkdfwr13cnlkvq.png" alt="services interaction" width="800" height="388"&gt;&lt;/a&gt;&lt;/p&gt;
Services Interactions



&lt;h3&gt;
  
  
  Endpoints
&lt;/h3&gt;

&lt;p&gt;The application includes a &lt;code&gt;RateLimitController&lt;/code&gt;, which processes requests matching &lt;code&gt;/api/v1/**&lt;/code&gt;. It checks the tenant’s bucket state using the &lt;code&gt;TenantBucketProvider&lt;/code&gt;. If the request is within limits, it is forwarded; otherwise, it is throttled.&lt;/p&gt;

&lt;h3&gt;
  
  
  Throttling
&lt;/h3&gt;

&lt;p&gt;Again, for the sake of simplicity, we &lt;strong&gt;Hard-Throttle&lt;/strong&gt; requests that exceed the tenant’s limits&lt;/p&gt;

&lt;h3&gt;
  
  
  Profiles
&lt;/h3&gt;

&lt;p&gt;The application supports two runtime profiles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;standalone&lt;/code&gt;: Uses the &lt;code&gt;StandaloneBucketProvider&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;distributed&lt;/code&gt;: Uses the &lt;code&gt;RedisBucketProvider&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;API rate limiting is essential for maintaining the stability, security, and fairness of APIs. By understanding its architecture, scaling mechanisms, and implementation strategies, developers can design robust systems that handle diverse usage patterns effectively. For a hands-on demonstration, check out the implementation code on &lt;a href="https://github.com/ahmedjaadi/api-rate-limiter" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>api</category>
      <category>springboot</category>
      <category>security</category>
    </item>
    <item>
      <title>Learn about Java cleaners and while you're at it you will also learn about Phantom references.</title>
      <dc:creator>Ahmed Jaad</dc:creator>
      <pubDate>Tue, 24 Dec 2024 23:42:16 +0000</pubDate>
      <link>https://dev.to/ahmedjaad/learn-about-java-cleaners-and-while-youre-at-it-you-will-also-learn-about-phantom-references-2feb</link>
      <guid>https://dev.to/ahmedjaad/learn-about-java-cleaners-and-while-youre-at-it-you-will-also-learn-about-phantom-references-2feb</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="/ahmedjaad" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F377351%2Fab21c59f-ecb6-489a-8630-eda766c9f9fd.JPG" alt="ahmedjaad"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://dev.to/ahmedjaad/java-cleaners-the-modern-way-to-manage-external-resources-4d4" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Java Cleaners: The Modern Way to Manage External Resources&lt;/h2&gt;
      &lt;h3&gt;Ahmed Jaad ・ Aug 13 '24&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#java&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#programming&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#coding&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#development&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;


</description>
      <category>java</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Spring MVC Unveiled: How It Leverages Servlet Technology</title>
      <dc:creator>Ahmed Jaad</dc:creator>
      <pubDate>Tue, 24 Dec 2024 05:29:44 +0000</pubDate>
      <link>https://dev.to/ahmedjaad/spring-mvc-unveiled-how-it-leverages-servlet-technology-41b8</link>
      <guid>https://dev.to/ahmedjaad/spring-mvc-unveiled-how-it-leverages-servlet-technology-41b8</guid>
      <description>&lt;ul&gt;
&lt;li&gt;&lt;p&gt;This is the second part of the &lt;a href="https://dev.to/ahmedjaad/series/29876"&gt;Inside Spring&lt;/a&gt; series. If you haven’t read the first part, &lt;a href="https://dev.to/ahmedjaad/servlet-the-foundation-of-java-web-technology-okh"&gt;Servlet: The Foundation of Java Web Technology&lt;/a&gt;, we recommend doing so even if you’re familiar with the topic, it is a great refresher.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We’ve mixed XML and annotation-based configurations to broaden your understanding of Spring and the Servlet API, and for illustration purposes, not a preference for XML, modern practices favor annotations.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;This article is accompanied by source code on &lt;a href="https://github.com/ahmedjaadi/spring-mvc-unveiled" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;. Following along with the code, while reading will help you better understand the concepts discussed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Unfortunately images here are of poor quality, for better quality, checkout the ones in the GitHub repository.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;



&lt;ul&gt;
&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;
Bootstrapping and Configuring Spring MVC

&lt;ul&gt;
&lt;li&gt;ApplicationContext Creation&lt;/li&gt;
&lt;li&gt;Self-Configuration&lt;/li&gt;
&lt;li&gt;Programmatic Initialization&lt;/li&gt;
&lt;li&gt;Hierarchical WebApplicationContext Structure&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

Dispatching Request

&lt;ul&gt;
&lt;li&gt;Key Workflow Steps&lt;/li&gt;
&lt;li&gt;HandlerExecutionChain&lt;/li&gt;
&lt;li&gt;HandlerAdapter and Invoking the Handler&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;How it all fits in with SpringBoot&lt;/li&gt;

&lt;li&gt;Conclusion&lt;/li&gt;

&lt;/ul&gt;

&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;Back in 2013, as I began exploring Spring, I had a basic grasp of Servlet technology but couldn’t quite understand why deploying a Spring MVC application required Tomcat, a Servlet container, despite not writing a single Servlet.&lt;/p&gt;

&lt;p&gt;I also wondered how Spring’s &lt;code&gt;ApplicationContext&lt;/code&gt; was initialized, or how Tomcat mapped HTTP requests without definitions in the deployment descriptor. Fast-forward 11 years, and with Spring Boot’s rise, answering these questions has only grown more challenging.&lt;/p&gt;

&lt;p&gt;In this article, we’ll attempt to answer these questions by exploring how Servlet technology bootstraps and configures a Spring MVC application, how Spring MVC dispatches requests to the right handlers, and finally, how all of this integrates seamlessly with Spring Boot.&lt;/p&gt;

&lt;p&gt;We won’t go into the details of the MVC pattern, the concept of a front controller, or the basics of the Spring Framework. It’s assumed that you already understand what the &lt;code&gt;ApplicationContext&lt;/code&gt; is and its role in a Spring application. If these concepts are new to you, I encourage exploring the many excellent resources available to learn about them.&lt;/p&gt;

&lt;h1&gt;
  
  
  Bootstrapping and Configuring Spring MVC
&lt;/h1&gt;

&lt;p&gt;Since you’re here, you likely know what &lt;a href="https://dev.to/ahmedjaad/servlet-the-foundation-of-java-web-technology-okh#what-is-a-servlet"&gt;a servlet is&lt;/a&gt;, so let’s view Spring MVC from a fresh perspective: it’s essentially one giant, powerful, and highly customizable servlet.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;📌 Note&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;While typically there’s one &lt;code&gt;DispatcherServlet&lt;/code&gt; in a Spring MVC application, multiple can be configured if needed.  Spring MVC creates and maintains one &lt;code&gt;ApplicationContext&lt;/code&gt; per &lt;code&gt;DispatcherServlet&lt;/code&gt;, each of these servlets operates in their own namespace and resources&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;At its core, Spring MVC revolves around a single servlet, the &lt;code&gt;DispatcherServlet&lt;/code&gt;, which handles every incoming request. Spring essentially tells the Servlet API:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;I’ll use you to bootstrap and configure myself. Once that’s done, forward all requests to me—I’ll handle them better.&lt;/p&gt;

&lt;p&gt;—  Spring MVC to Servlet API&lt;/p&gt;
&lt;/blockquote&gt;


&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fih057b7o7bvydnp4zen5.png" alt="spring mvc overview" width="800" height="361"&gt;Spring MVC Overview



&lt;p&gt;&lt;em&gt;Here’s how Spring MVC leverages Servlet technology to bootstrap and configure itself:&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Request Mapping&lt;/strong&gt;: The servlet container maps all requests to the &lt;code&gt;DispatcherServlet&lt;/code&gt;, enabling Spring MVC to control the request-handling lifecycle.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;ApplicationContext Creation&lt;/strong&gt;: The servlet container instantiates and initializes the &lt;code&gt;DispatcherServlet&lt;/code&gt;, which itself initializes the Spring &lt;code&gt;ApplicationContext&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Self-Configuration&lt;/strong&gt;: When the servlet container calls &lt;code&gt;init()&lt;/code&gt; on the &lt;code&gt;DispatcherServlet&lt;/code&gt;, it configures itself based on the application’s setup.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Programmatic Initialization&lt;/strong&gt;: Spring allows developers to influence the initialization process using the &lt;code&gt;ServletContainerInitializer&lt;/code&gt; interface and the &lt;code&gt;@HandlesTypes&lt;/code&gt; annotation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Hierarchical WebApplicationContext Structure&lt;/strong&gt;: Spring uses the &lt;code&gt;ContextLoaderListener&lt;/code&gt;, an implementation of &lt;code&gt;ServletContextListener&lt;/code&gt;, to create and initialize a root &lt;code&gt;WebApplicationContext&lt;/code&gt;, establishing a hierarchy where the root context provides shared beans to all &lt;code&gt;DispatcherServlet&lt;/code&gt; instances.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There isn’t that much more to say about the first point. Spring maps requests to the &lt;code&gt;DispatcherServlet&lt;/code&gt; using the &lt;code&gt;&amp;lt;servlet-mapping&amp;gt;&lt;/code&gt; element in &lt;code&gt;web.xml&lt;/code&gt; or the &lt;code&gt;urlPatterns&lt;/code&gt; attribute of the &lt;code&gt;@WebServlet&lt;/code&gt; annotation. For dynamic servlet registration, it relies on the &lt;code&gt;addMapping()&lt;/code&gt; method of the &lt;code&gt;ServletRegistration&lt;/code&gt; interface.&lt;/p&gt;

&lt;p&gt;Now, let’s take a closer look at the remaining four points.&lt;/p&gt;
&lt;h2&gt;
  
  
  ApplicationContext Creation
&lt;/h2&gt;


&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fraw.githubusercontent.com%2Fahmedjaadi%2Fspring-mvc-unveiled%2Frefs%2Fheads%2Fmain%2Fdoc%2Fcreate_wep_app_context.png" alt="create wep app context" width="800" height="306"&gt;Creating WebApplicationContext



&lt;p&gt;When a &lt;code&gt;DispatcherServlet&lt;/code&gt; is registered statically, either via &lt;code&gt;web.xml&lt;/code&gt; or the &lt;code&gt;@WebServlet&lt;/code&gt; annotation, the servlet container uses its default no-argument constructor to instantiate it, the servlet container then calls the servlet’s &lt;code&gt;init()&lt;/code&gt; lifecycle method.  &lt;/p&gt;

&lt;p&gt;Spring MVC takes advantage of the &lt;code&gt;init()&lt;/code&gt; method call by loading a configuration file named &lt;code&gt;[servletName]-servlet.xml&lt;/code&gt; from the WEB-INF directory, and then creates and initializes an instance of &lt;code&gt;WebApplicationContext&lt;/code&gt;, a sub-interface of &lt;code&gt;ApplicationContext&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Spring offers flexibility through the &lt;code&gt;contextConfigLocation&lt;/code&gt; initialization parameter, which allows you to specify alternative XML configuration files. Similarly, the &lt;code&gt;contextClass&lt;/code&gt; parameter lets you define the &lt;code&gt;ApplicationContext&lt;/code&gt; implementation to use, typically a class like &lt;code&gt;AnnotationConfigWebApplicationContext.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;For greater control, the &lt;code&gt;DispatcherServlet&lt;/code&gt; provides methods to set these values. A preferred approach is to extend the &lt;code&gt;DispatcherServlet&lt;/code&gt; and override its default constructor to configure these parameters programmatically.&lt;/p&gt;
&lt;h3&gt;
  
  
  Practical Example: Dedicated DispatcherServlet for Integration
&lt;/h3&gt;

&lt;p&gt;In our banking application, suppose we want a &lt;code&gt;DispatcherServlet&lt;/code&gt; named &lt;code&gt;integrationAppServlet&lt;/code&gt; dedicated to third-party integrations. We can register it in &lt;code&gt;web.xml&lt;/code&gt; as follows:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;web.xml&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight xml"&gt;&lt;code&gt;
        &lt;span class="nt"&gt;&amp;lt;servlet&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;servlet-name&amp;gt;&lt;/span&gt;integrationAppServlet&lt;span class="nt"&gt;&amp;lt;/servlet-name&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;servlet-class&amp;gt;&lt;/span&gt;org.springframework.web.servlet.DispatcherServlet&lt;span class="nt"&gt;&amp;lt;/servlet-class&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;load-on-startup&amp;gt;&lt;/span&gt;1&lt;span class="nt"&gt;&amp;lt;/load-on-startup&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;/servlet&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;servlet-mapping&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;servlet-name&amp;gt;&lt;/span&gt;integrationAppServlet&lt;span class="nt"&gt;&amp;lt;/servlet-name&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;url-pattern&amp;gt;&lt;/span&gt;/integration/*&lt;span class="nt"&gt;&amp;lt;/url-pattern&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;/servlet-mapping&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring MVC will then look for a configuration file named &lt;code&gt;WEB-INF/integrationAppServlet-servlet.xml&lt;/code&gt;. Here’s how it might look:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;integrationAppServlet-servlet.xml&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight xml"&gt;&lt;code&gt;
            &lt;span class="c"&gt;&amp;lt;!-- xmlns declarations removed for brevity --&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;beans&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;context:component-scan&lt;/span&gt; &lt;span class="na"&gt;base-package=&lt;/span&gt;&lt;span class="s"&gt;"spring_mvc_unveiled.integration"&lt;/span&gt;&lt;span class="nt"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/beans&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This setup instructs Spring MVC to scan the &lt;code&gt;spring_mvc_unveiled.integration&lt;/code&gt; package for beans, create a &lt;code&gt;WebApplicationContext&lt;/code&gt; with them, and associate that context with the &lt;code&gt;integrationAppServlet&lt;/code&gt;. This servlet will handle all requests with the &lt;code&gt;/integration&lt;/code&gt; URL pattern.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;📌 Note&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;The static registration of &lt;code&gt;DispatcherServlet&lt;/code&gt; is demonstrated in &lt;code&gt;web.xml&lt;/code&gt; and &lt;code&gt;WEB-INF/integrationAppServlet-servlet.xml&lt;/code&gt;.  For &lt;code&gt;@WebServlet&lt;/code&gt; registration, see the &lt;code&gt;CustomerAppServlet&lt;/code&gt; class and its nested &lt;code&gt;CustomerAppApplicationContext&lt;/code&gt; class.&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Self-Configuration
&lt;/h2&gt;

&lt;p&gt;Spring not only creates the &lt;code&gt;WebApplicationContext&lt;/code&gt; for the &lt;code&gt;DispatcherServlet&lt;/code&gt; during its &lt;code&gt;init()&lt;/code&gt; method call but also registers essential beans called &lt;a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-servlet/special-bean-types.html" rel="noopener noreferrer"&gt;Special Bean Types&lt;/a&gt;.&lt;br&gt;
&lt;code&gt;DispatcherServlet&lt;/code&gt; delegates the real work of processing requests to these beans, there are eight such bean types in total, but discussing all of them is beyond the scope of this article. To provide clarity on what Spring MVC configures within the &lt;code&gt;DispatcherServlet,&lt;/code&gt; we’ll briefly highlight three key examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;HandlerMapping&lt;/code&gt;: This bean helps &lt;code&gt;DispatcherServlet&lt;/code&gt; determine the bean that will handle a request, for instance in our banking application, in the &lt;code&gt;BalanceController&lt;/code&gt; class we have the &lt;code&gt;balance()&lt;/code&gt; method which is annotated with &lt;code&gt;@GetMapping&lt;/code&gt; annotation, when a &lt;code&gt;GET&lt;/code&gt; &lt;code&gt;/customer/balance&lt;/code&gt; request comes &lt;code&gt;DispatcherServlet&lt;/code&gt;'s way, it will ask the &lt;code&gt;HandlerMapping&lt;/code&gt; bean to map the request to the right handler, the &lt;code&gt;HandlerMapping&lt;/code&gt; bean will then map the request to the &lt;code&gt;BalanceController#balance&lt;/code&gt; method. The implementation of &lt;code&gt;HandlerMapping&lt;/code&gt; that supports mapping of methods annotated with &lt;code&gt;@RequestMapping&lt;/code&gt; is &lt;code&gt;RequestMappingHandlerMapping&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;



&lt;p&gt;&lt;a id="handler_exception_resolver"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;HandlerExceptionResolver&lt;/code&gt;: If an exception is thrown during mapping or processing of a request,&lt;code&gt;DispatcherServlet&lt;/code&gt; will ask a bean of type &lt;code&gt;HandlerExceptionResolver&lt;/code&gt; to determine an exception handler. You’ve probably used the &lt;code&gt;@ControllerAdvice&lt;/code&gt; and &lt;code&gt;@ExceptionHandler&lt;/code&gt; annotation to globally handle exceptions in your applications, you might have thought it was magic that calls you methods, I’m here to tell it is not, it’s actual an implementation of &lt;code&gt;HandlerExceptionResolver&lt;/code&gt; by name &lt;code&gt;ExceptionHandlerExceptionResolver&lt;/code&gt; that does this&lt;/li&gt;
&lt;/ul&gt;



&lt;p&gt;&lt;a id="view_resolver"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;ViewResolver&lt;/code&gt;: When your handler return a String, Spring MVC assumes it is a name of a view, and the &lt;code&gt;DispatcherServlet&lt;/code&gt; will ask a bean of type &lt;code&gt;ViewResolver&lt;/code&gt; to resolve the real view that will be returned to the client&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As already mentioned Spring MVC configures the &lt;code&gt;DispatcherServlet&lt;/code&gt; with these beans by first checking if the programmer defined these beans, if not it will go ahead with the default strategy that creates all the beans that the &lt;code&gt;DispatcherServlet&lt;/code&gt; needs.&lt;/p&gt;

&lt;p&gt;If customization is needed, you can either provide your own beans of these types, and Spring will pick them up, or use the &lt;code&gt;@EnableWebMvc&lt;/code&gt; annotation with the &lt;code&gt;WebMvcConfigurer&lt;/code&gt; interface. This approach allows fine-grained control over the Spring MVC flow while still leveraging the framework’s defaults where needed.&lt;/p&gt;
&lt;h2&gt;
  
  
  Programmatic Initialization
&lt;/h2&gt;

&lt;p&gt;Programmers can implement the &lt;code&gt;WebApplicationInitializer&lt;/code&gt; interface, which includes a single method: &lt;code&gt;onStartup(ServletContext servletContext)&lt;/code&gt;. Spring MVC calls this method and provides the &lt;code&gt;ServletContext&lt;/code&gt; instance, allowing developers to perform tasks during the application startup. This gives developers a say over the initialization process.&lt;/p&gt;

&lt;p&gt;But how does Spring achieve this? It uses &lt;code&gt;SpringServletContainerInitializer&lt;/code&gt;, an implementation of &lt;a href="https://dev.to/ahmedjaad/servlet-the-foundation-of-java-web-technology-okh#servletcontainerinitializer"&gt;ServletContainerInitializer&lt;/a&gt; which is annotated with &lt;code&gt;@HandlesTypes(WebApplicationInitializer.class)&lt;/code&gt;. As explained in the &lt;a href="https://dev.to/ahmedjaad/servlet-the-foundation-of-java-web-technology-okh#servletcontainerinitializer"&gt;ServletContainerInitializer&lt;/a&gt; section, the servlet container passes all instances of &lt;code&gt;WebApplicationInitializer&lt;/code&gt; to the &lt;code&gt;onStartup&lt;/code&gt; method of &lt;code&gt;SpringServletContainerInitializer&lt;/code&gt;. Spring then invokes the &lt;code&gt;onStartup&lt;/code&gt; method of each &lt;code&gt;WebApplicationInitializer&lt;/code&gt; instance and provides the &lt;code&gt;ServletContext&lt;/code&gt; instance.&lt;/p&gt;
&lt;h3&gt;
  
  
  Practical Example: Dedicated DispatcherServlet for Backoffice
&lt;/h3&gt;

&lt;p&gt;Given the multi-module nature of our banking app, a dedicated &lt;code&gt;DispatcherServlet&lt;/code&gt; is needed to handle backoffice requests under the &lt;code&gt;/back_office&lt;/code&gt; URL path. By implementing the &lt;code&gt;WebApplicationInitializer&lt;/code&gt; interface, we can dynamically register a &lt;code&gt;DispatcherServlet&lt;/code&gt; without relying on annotations or &lt;code&gt;web.xml&lt;/code&gt;. Here’s an example:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;BackOfficeAppInitializer.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;
        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;onStartup&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ServletContext&lt;/span&gt; &lt;span class="n"&gt;servletContext&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;webApplicationContext&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;AnnotationConfigWebApplicationContext&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="n"&gt;webApplicationContext&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;register&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;BackOfficeWebConfig&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;dispatcherServlet&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;DispatcherServlet&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;webApplicationContext&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;dispatcher&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;servletContext&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addServlet&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"backOfficeAppServlet"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dispatcherServlet&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;dispatcher&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setLoadOnStartup&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;dispatcher&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addMapping&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/back_office/*"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This programmatic approach provides full control over how the &lt;code&gt;DispatcherServlet&lt;/code&gt; and &lt;code&gt;WebApplicationContext&lt;/code&gt; are created and configured, making it a powerful alternative to static registration.&lt;/p&gt;

&lt;p&gt;Spring provides a convenient abstract implementation of &lt;code&gt;WebApplicationInitializer&lt;/code&gt; in &lt;code&gt;AbstractAnnotationConfigDispatcherServletInitializer&lt;/code&gt;, that makes it easy to initialize &lt;code&gt;DispatcherServlet&lt;/code&gt; based on Java config classes. Check out our &lt;code&gt;OthersAppServlet&lt;/code&gt; that extends the abstract class.&lt;/p&gt;

&lt;h2&gt;
  
  
  Hierarchical WebApplicationContext Structure
&lt;/h2&gt;

&lt;p&gt;Spring leverages the &lt;a href="https://dev.to/ahmedjaad/servlet-the-foundation-of-java-web-technology-okh#listeners"&gt;ServletContextListener&lt;/a&gt; interface to support a &lt;a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-servlet/context-hierarchy.html" rel="noopener noreferrer"&gt;hierarchical structure&lt;/a&gt; for &lt;code&gt;WebApplicationContexts&lt;/code&gt;, enabling shared beans across multiple contexts. This is achieved through &lt;code&gt;ContextLoaderListener&lt;/code&gt;, Spring’s implementation of &lt;code&gt;ServletContextListener&lt;/code&gt;. The &lt;code&gt;ContextLoaderListener&lt;/code&gt; creates a root &lt;code&gt;WebApplicationContext&lt;/code&gt; that acts as the parent context for all child contexts in the application. Beans defined in the root context are accessible to its child contexts, but not vice versa.  To use this feature, developers need to register &lt;code&gt;ContextLoaderListener&lt;/code&gt; as a listener via one of the following methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;web.xml&lt;/code&gt; &lt;code&gt;&amp;lt;listener&amp;gt;&lt;/code&gt; element.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;@WebListener&lt;/code&gt; annotation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Programmatically with the &lt;code&gt;ServletContext.&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Spring checks for the &lt;code&gt;contextClass&lt;/code&gt; parameter at the &lt;code&gt;web.xml&lt;/code&gt; &lt;code&gt;&amp;lt;context-param&amp;gt;&lt;/code&gt; level to determine the context class to initialize. If not specified, it defaults to the &lt;code&gt;contextConfigLocation&lt;/code&gt; parameter. Spring also provides an overloaded constructor where you can pass in a &lt;code&gt;WebApplicationContext&lt;/code&gt;, this is useful when the &lt;code&gt;ContextLoaderListener&lt;/code&gt; is registered dynamically  &lt;/p&gt;

&lt;p&gt;This is the second point in the application lifecycle where Spring creates and configures a &lt;code&gt;WebApplicationContext&lt;/code&gt;, the first being within the &lt;code&gt;DispatcherServlet.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgvp03n57tokue9m92klu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgvp03n57tokue9m92klu.png" alt="hierarchical context" width="800" height="528"&gt;&lt;/a&gt;&lt;/p&gt;
Hierarchical WebContext



&lt;h3&gt;
  
  
  Practical Example: Shared DAO Beans
&lt;/h3&gt;

&lt;p&gt;In our banking application, even though it is modular, certain beans are shared across modules, such as infrastructure or business logic components. For instance, data access layer (DAO) beans are common to all modules, and maintaining separate versions in each &lt;code&gt;WebApplicationContext&lt;/code&gt; would be inefficient. A root application context is the ideal solution for sharing these beans.&lt;/p&gt;

&lt;p&gt;To set up a root context, the &lt;code&gt;ContextLoaderListener&lt;/code&gt; can be registered in &lt;code&gt;web.xml&lt;/code&gt; like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;web.xml&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight xml"&gt;&lt;code&gt;
    &lt;span class="nt"&gt;&amp;lt;listener&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;listener-class&amp;gt;&lt;/span&gt;org.springframework.web.context.ContextLoaderListener&lt;span class="nt"&gt;&amp;lt;/listener-class&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/listener&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;context-param&amp;gt;&lt;/span&gt;
           &lt;span class="nt"&gt;&amp;lt;param-name&amp;gt;&lt;/span&gt;contextClass&lt;span class="nt"&gt;&amp;lt;/param-name&amp;gt;&lt;/span&gt;
           &lt;span class="nt"&gt;&amp;lt;param-value&amp;gt;&lt;/span&gt;spring_mvc_unveiled.root.RootApplicationContext&lt;span class="nt"&gt;&amp;lt;/param-value&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/context-param&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;📌 Note&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;This can also be achieved using the &lt;code&gt;@WebListener&lt;/code&gt; annotation. For implementation details, refer to our &lt;code&gt;RootContextLoaderListener&lt;/code&gt; class and its Javadoc.&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;


&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8yeg4vgqgcem7l8hzfmj.png" alt="startup process" width="800" height="217"&gt;Spring MVC Startup Process


&lt;h1&gt;
  
  
  Dispatching Request
&lt;/h1&gt;

&lt;p&gt;The &lt;code&gt;DispatcherServlet&lt;/code&gt; is at the core of Spring MVC, functioning as the front controller for the application. For every incoming request, the servlet container invokes the &lt;code&gt;service()&lt;/code&gt; method of the &lt;code&gt;DispatcherServlet&lt;/code&gt;, just as it does for &lt;a href="https://dev.to/ahmedjaad/servlet-the-foundation-of-java-web-technology-okh#servlet"&gt;any other servlet&lt;/a&gt; in the Servlet API lifecycle. From there, the &lt;code&gt;DispatcherServlet&lt;/code&gt; takes charge, leveraging this foundational servlet mechanism to prepare and dispatch the request to the appropriate handler, showcasing how Spring MVC is seamlessly built on top of the Servlet API.&lt;/p&gt;
&lt;h2&gt;
  
  
  Key Workflow Steps
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;DispatcherServlet&lt;/code&gt; organizes its workflow by delegating specific tasks to specialized components, adhering to the separation of concerns principle.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The &lt;code&gt;DispatcherServlet&lt;/code&gt; processes requests in four primary steps:&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Prepare the Request&lt;/strong&gt;: Performs cross-cutting tasks such as determining the locale, resolving multipart requests, and storing the request attributes in the &lt;code&gt;RequestContextHolder&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Determine and Execute the Handler&lt;/strong&gt;: Uses a &lt;code&gt;HandlerMapping&lt;/code&gt; to identify the handler and invokes it through a &lt;code&gt;HandlerAdapter&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Resolve Exceptions&lt;/strong&gt;: Delegates exception handling to a &lt;code&gt;HandlerExceptionResolver&lt;/code&gt;. Also mentioned here&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Prepare the Response&lt;/strong&gt;: Involves tasks like resolving the &lt;code&gt;View&lt;/code&gt; by a &lt;code&gt;ViewResolver&lt;/code&gt; to determine how to render the response. Also mentioned here&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;


&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy3u68iudow6x9djuw32t.png" alt="request process flow" width="800" height="136"&gt;Request Process Flow



&lt;p&gt;This section focuses on the second step: determining and executing the handler, let us see the components involved in this process.&lt;/p&gt;
&lt;h2&gt;
  
  
  HandlerExecutionChain
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;HandlerMapping&lt;/code&gt; does not directly return a handler but instead an instance of &lt;code&gt;HandlerExecutionChain&lt;/code&gt;, which bundles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The Handler&lt;/strong&gt;: This is the object that processes the request. It can be any &lt;code&gt;Object&lt;/code&gt;, offering flexibility in design. For example, &lt;code&gt;HandlerMethod&lt;/code&gt; is a &lt;code&gt;handler&lt;/code&gt; that represents controller methods annotated with &lt;code&gt;@RequestMapping&lt;/code&gt; and similar annotations (&lt;code&gt;@GetMapping&lt;/code&gt;, &lt;code&gt;@PostMapping&lt;/code&gt;, etc.)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Interceptors&lt;/strong&gt;: These are pre- and post-processing hooks, implemented using &lt;code&gt;HandlerInterceptor&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The &lt;code&gt;preHandle()&lt;/code&gt; method runs before the handler and can block the request.&lt;/li&gt;
&lt;li&gt;  The &lt;code&gt;postHandle()&lt;/code&gt; method runs after the handler and can modify the response.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Interceptors are reusable and can be applied to multiple handlers. For example, a security interceptor can validate credentials across all handlers for secured paths. While similar to servlet filters, interceptors are more powerful as they integrate into the Spring MVC workflow.&lt;/p&gt;


&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe68z83gwqv7hi6e2hfnf.png" alt="handler execution chain" width="800" height="147"&gt;Handler Execution Chain


&lt;h3&gt;
  
  
  Example: HandlerMethod
&lt;/h3&gt;

&lt;p&gt;A handler is referenced as an &lt;code&gt;Object&lt;/code&gt; by &lt;code&gt;HandlerExecutionChain,&lt;/code&gt; meaning that, for the &lt;code&gt;DispatcherServlet&lt;/code&gt;, a handler is essentially just an Object. The real type of the handler can be anything; for instance, it could be a &lt;code&gt;HandlerMethod&lt;/code&gt;. A &lt;code&gt;HandlerMethod&lt;/code&gt; represents methods annotated with &lt;code&gt;@RequestMapping&lt;/code&gt; and its variants (like &lt;code&gt;@GetMapping,&lt;/code&gt; &lt;code&gt;@PostMapping)&lt;/code&gt;. When a request is received, Spring creates a &lt;code&gt;HandlerMethod&lt;/code&gt; bean for each annotated method, allowing the adapter to call the method via reflection.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;HandlerMethod&lt;/code&gt; does more than wrap a reference to the method, it also maintains state to represent the arguments and return values of the method. This is essential because it allows Spring to dynamically resolve method parameters (such as HTTP request data) and invoke the method with the correct context at runtime.&lt;/p&gt;
&lt;h3&gt;
  
  
  Example: Registering an Interceptor
&lt;/h3&gt;

&lt;p&gt;Developers are responsible to define their interceptors and register them to Spring MVC this can be achieved by using the &lt;code&gt;@EnableWebMvc&lt;/code&gt; annotation and &lt;code&gt;WebMvcConfigurer&lt;/code&gt; interface. In our banking application say that we want to intercept &lt;code&gt;/balance&lt;/code&gt; path, we will register it like below:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;CustomerWebConfig&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;
    &lt;span class="nd"&gt;@Configuration&lt;/span&gt;
    &lt;span class="nd"&gt;@EnableWebMvc&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CustomerWebConfig&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;WebMvcConfigurer&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;addInterceptors&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InterceptorRegistry&lt;/span&gt; &lt;span class="n"&gt;registry&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/*
            the path pattern is relative to the DispatcherServlet root path
            in this case /customer
    */&lt;/span&gt;
            &lt;span class="n"&gt;registry&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;addInterceptor&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;BalanceInterceptor&lt;/span&gt;&lt;span class="o"&gt;()).&lt;/span&gt;&lt;span class="na"&gt;addPathPatterns&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/**"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the &lt;code&gt;BalanceInterceptor&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;BalanceInterceptor.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BalanceInterceptor&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;HandlerInterceptor&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;preHandle&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;HttpServletRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;HttpServletResponse&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;handler&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Logic goes here&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Return true to continue; false to block the request&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  HandlerAdapter and Invoking the Handler
&lt;/h2&gt;

&lt;p&gt;Since handlers are generic &lt;code&gt;Object&lt;/code&gt; instances, the &lt;code&gt;DispatcherServlet&lt;/code&gt; uses &lt;code&gt;HandlerAdapter&lt;/code&gt; objects to invoke them. Each &lt;code&gt;HandlerAdapter&lt;/code&gt; knows how to handle a specific type of handler. For example, &lt;code&gt;RequestMappingHandlerAdapter&lt;/code&gt; knows how to invoke &lt;code&gt;HandlerMethod&lt;/code&gt;, a handler for methods annotated with &lt;code&gt;@RequestMapping&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The two key methods of &lt;code&gt;HandlerAdapter&lt;/code&gt; are:&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;supports()&lt;/code&gt;&lt;/strong&gt;: Determines if the adapter can handle a given handler type.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;handle()&lt;/code&gt;&lt;/strong&gt;: Invokes the handler using the request and response objects, returning a &lt;code&gt;ModelAndView&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For each handler, that the &lt;code&gt;DispatcherServlet&lt;/code&gt; encounters there must be an adapter that supports it, otherwise, the &lt;code&gt;DispatcherServlet&lt;/code&gt; will throw a &lt;code&gt;ServletException&lt;/code&gt;.  As already mentioned, &lt;code&gt;HandlerAdapter&lt;/code&gt; is one of the &lt;a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-servlet/special-bean-types.html" rel="noopener noreferrer"&gt;Special Bean Types&lt;/a&gt;, and the default strategy of the &lt;code&gt;DispatcherServlet&lt;/code&gt; creates four beans of type &lt;code&gt;HandlerAdapter&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now that we’ve explored the key components the &lt;code&gt;DispatcherServlet&lt;/code&gt; uses to locate and invoke handlers, let’s see the whole flow:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc73l1vblafq1343nd4ye.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc73l1vblafq1343nd4ye.png" alt="overall handling request" width="800" height="171"&gt;&lt;/a&gt;&lt;/p&gt;
Spring MVC Handling Request



&lt;p&gt;Below is a simplified code flow:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DispatcherServlet.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;
            &lt;span class="nc"&gt;HandlerExecutionChain&lt;/span&gt;  &lt;span class="n"&gt;executionChain&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;getExecutionChain&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="nc"&gt;HandlerAdapter&lt;/span&gt; &lt;span class="n"&gt;adapter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;getHandlerAdapter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;executionChain&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getHandler&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(!&lt;/span&gt;&lt;span class="n"&gt;executionChain&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;applyPreHandle&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;&lt;span class="c1"&gt;// Request blocked by one of the preHandle() methods&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;
            &lt;span class="c1"&gt;// Use the adapter to invoke the handler&lt;/span&gt;
            &lt;span class="nc"&gt;ModelAndView&lt;/span&gt;  &lt;span class="n"&gt;mv&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;adapter&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;handle&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;executionChain&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getHandler&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
            &lt;span class="n"&gt;executionChain&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;applyPostHandle&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mv&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

            &lt;span class="c1"&gt;// continue with preparing the response&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;📌 Note&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;This code is a simplified representation of the actual Spring Framework implementation to clarify the flow.&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Code Highlights:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;getExecutionChain(request)&lt;/code&gt;: Iterates through all &lt;code&gt;HandlerMapping&lt;/code&gt; beans to find a &lt;code&gt;HandlerExecutionChain&lt;/code&gt; for the request. Returns &lt;code&gt;null&lt;/code&gt; if none match.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;getHandlerAdapter(handler)&lt;/code&gt;: Iterates through &lt;code&gt;HandlerAdapter&lt;/code&gt; beans, calling their &lt;code&gt;supports()&lt;/code&gt; method. Throws &lt;code&gt;ServletException&lt;/code&gt; if no adapter supports the handler.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;applyPreHandle(request, response)&lt;/code&gt;: Executes the &lt;code&gt;preHandle()&lt;/code&gt; methods of all applicable &lt;code&gt;HandlerInterceptor&lt;/code&gt; objects. If any returns &lt;code&gt;false&lt;/code&gt;, the request is blocked.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;adapter.handle()&lt;/code&gt;: Delegates the actual invocation of the handler to the appropriate &lt;code&gt;HandlerAdapter&lt;/code&gt;, which knows how to call it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;applyPostHandle(request, response, mv)&lt;/code&gt;: Executes the &lt;code&gt;postHandle()&lt;/code&gt; methods of all interceptors after the handler has processed the request.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  How it all fits in with SpringBoot
&lt;/h1&gt;

&lt;p&gt;This text wouldn’t be complete without pointing out how all of this is related to Spring Boot. Spring Boot simplifies the process of setting up and running a Spring MVC application by removing much of the boilerplate configuration associated with traditional setups. Let’s explore how Spring Boot makes this possible and how it integrates seamlessly with the Servlet technology we’ve discussed so far.&lt;/p&gt;

&lt;h2&gt;
  
  
  Embedded Servlet Container
&lt;/h2&gt;

&lt;p&gt;One of the key features of Spring Boot is its ability to bundle an embedded servlet container, such as Tomcat, Jetty, or Undertow. Instead of deploying your application to an external servlet container, Spring Boot packages your application as a "fat JAR" that includes everything needed to run the application. This allows you to run your application as a standalone Java process, simplifying deployment and enabling portability.&lt;/p&gt;

&lt;p&gt;When your Spring Boot application starts, it initializes the embedded servlet container by using the &lt;code&gt;EmbeddedServletContainerFactory&lt;/code&gt;. This factory is responsible for configuring and starting the servlet container, allowing Spring Boot to dynamically register the &lt;code&gt;DispatcherServlet&lt;/code&gt; and other components as part of the initialization process.&lt;/p&gt;

&lt;h2&gt;
  
  
  @EnableAutoConfiguration
&lt;/h2&gt;

&lt;p&gt;Spring Boot further reduces complexity through the &lt;code&gt;@EnableAutoConfiguration&lt;/code&gt; annotation. This annotation scans the classpath for Spring components and configuration files, automatically creating and wiring the necessary beans, including the &lt;code&gt;DispatcherServlet&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;It detects the presence of Spring MVC-related libraries and automatically configures a &lt;code&gt;DispatcherServlet&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It creates and registers default components such as &lt;code&gt;HandlerMapping&lt;/code&gt;, &lt;code&gt;HandlerAdapter&lt;/code&gt;, and &lt;code&gt;ViewResolver&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It even sets up default error handling, static resource serving, and other conveniences out of the box.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Automatic Inclusion of @EnableWebMvc
&lt;/h2&gt;

&lt;p&gt;Spring Boot automatically includes &lt;code&gt;@EnableWebMvc&lt;/code&gt; when Spring MVC is present in your application. This ensures that Spring MVC’s default configuration is applied without requiring explicit inclusion of the annotation. Developers can still override and customize these configurations by implementing the &lt;code&gt;WebMvcConfigurer&lt;/code&gt; interface if necessary.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bringing It All Together
&lt;/h2&gt;

&lt;p&gt;With Spring Boot, setting up a Spring MVC application no longer requires extensive configuration. It leverages the power of Spring’s core framework while making it easier to focus on business logic rather than infrastructure. By bundling everything into a single fat JAR, providing embedded servlet containers, and automatically configuring essential components, Spring Boot transforms the development and deployment experience.&lt;/p&gt;

&lt;p&gt;This simplification, combined with the flexibility to customize as needed, makes Spring Boot a natural choice for modern Java web application development.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;In this article, we explored how Spring leverages key features of Servlet technology to bootstrap itself and efficiently dispatch requests. From understanding the foundational role of the &lt;code&gt;DispatcherServlet&lt;/code&gt; to examining how &lt;code&gt;RequestMapping&lt;/code&gt; and &lt;code&gt;HandlerAdapter&lt;/code&gt; work together to route and process requests, we also delved into hierarchical &lt;code&gt;WebApplicationContext&lt;/code&gt; structures and Spring’s self-configuration mechanisms.&lt;/p&gt;

&lt;p&gt;Mastering these concepts is an essential step toward deepening your understanding of the Spring framework, moving beyond basic usage to appreciating the underlying architecture and design principles.&lt;/p&gt;

&lt;p&gt;To solidify your learning, I encourage you to experiment with the accompanying code provided in this article. Use it as your playground to test and explore how Spring MVC works behind the scenes. Additionally, for further reading and reference, the &lt;a href="https://docs.spring.io/spring-framework/reference/index.html" rel="noopener noreferrer"&gt;Spring Framework Reference Documentation&lt;/a&gt; is an invaluable resource.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Please like and follow for more incoming Java/Spring contents&lt;/em&gt;.&lt;br&gt;
&lt;em&gt;Leave comments for questions or any further clarification&lt;/em&gt;&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>java</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>🚀 New article alert! Dive into "Servlet: The Foundation of Java Web Technology" and explore the backbone of Java web development. From handling HTTP requests to enabling frameworks like Spring MVC, servlets are where it all begins.</title>
      <dc:creator>Ahmed Jaad</dc:creator>
      <pubDate>Sun, 22 Dec 2024 23:38:34 +0000</pubDate>
      <link>https://dev.to/ahmedjaad/new-article-alert-dive-into-servlet-the-foundation-of-java-web-technology-and-explore-the-24hh</link>
      <guid>https://dev.to/ahmedjaad/new-article-alert-dive-into-servlet-the-foundation-of-java-web-technology-and-explore-the-24hh</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="/ahmedjaad" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F377351%2Fab21c59f-ecb6-489a-8630-eda766c9f9fd.JPG" alt="ahmedjaad"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://dev.to/ahmedjaad/servlet-the-foundation-of-java-web-technology-okh" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Servlet: The Foundation of Java Web Technology&lt;/h2&gt;
      &lt;h3&gt;Ahmed Jaad ・ Dec 22 '24&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#java&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#spring&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#springboot&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#web&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;


</description>
      <category>java</category>
      <category>webdev</category>
      <category>development</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Servlet: The Foundation of Java Web Technology</title>
      <dc:creator>Ahmed Jaad</dc:creator>
      <pubDate>Sun, 22 Dec 2024 01:17:09 +0000</pubDate>
      <link>https://dev.to/ahmedjaad/servlet-the-foundation-of-java-web-technology-okh</link>
      <guid>https://dev.to/ahmedjaad/servlet-the-foundation-of-java-web-technology-okh</guid>
      <description>&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We’ve mixed XML and annotation-based configurations to broaden your understanding of Servlet API, and for illustration purposes, not a preference for XML, modern practices favor annotations.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;This article is accompanied by source code on &lt;a href="https://github.com/ahmedjaadi/servlet-basics" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;. Following along with the code, while reading will help you better understand the concepts discussed.  &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;



&lt;ul&gt;
&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;What is a Servlet?&lt;/li&gt;
&lt;li&gt;Servlet Container&lt;/li&gt;
&lt;li&gt;
Servlet API

&lt;ul&gt;
&lt;li&gt;Servlet&lt;/li&gt;
&lt;li&gt;Filters&lt;/li&gt;
&lt;li&gt;ServletContext&lt;/li&gt;
&lt;li&gt;Listeners&lt;/li&gt;
&lt;li&gt;ServletContainerInitializer&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Registering Components with the Servlet Container&lt;/li&gt;

&lt;li&gt;Conclusion&lt;/li&gt;

&lt;/ul&gt;

&lt;h1&gt;
  
  
  Introduction
&lt;/h1&gt;

&lt;p&gt;If you’re a Spring developer like me, you’ve likely encountered mentions of the &lt;code&gt;DispatcherServlet&lt;/code&gt; in articles or books. It’s often described as the "&lt;strong&gt;Front Controller&lt;/strong&gt;" of the Spring MVC framework, accompanied by well-crafted diagrams explaining the concept.&lt;/p&gt;

&lt;p&gt;But in my experience, many of these resources fail to address a crucial question: &lt;strong&gt;How does Spring MVC make the &lt;code&gt;DispatcherServlet&lt;/code&gt; its Front Controller?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Answering this question requires a solid understanding of the Servlet technology ecosystem, which forms the backbone of Spring MVC. Gaining this knowledge can elevate you from being an okay Spring Boot developer to a Spring professional with in-depth expertise.&lt;/p&gt;

&lt;p&gt;In this article, we’ll begin by exploring the core concepts of Servlet technology. Then, in the next parts of this series, we’ll uncover how Spring leverages these concepts to build the powerful Spring MVC framework.&lt;/p&gt;

&lt;h1&gt;
  
  
  What is a Servlet?
&lt;/h1&gt;

&lt;p&gt;If you’ve been asked this question in an interview, I’d like to know what your answer was, this is such a multifaceted question I myself don’t know if I could give a straight answer. Let us look at some ways one can answer this question&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Servlet is part of the suite of specifications that make up Jakarta EE. Formerly known as Java Enterprise Edition(Java EE), it is a set of specifications that standardizes how we write Java enterprise applications, Jakarta Servlet specifies server-side API for handling HTTP request and responses. More commonly known specifications are Jakarta Persistence(JPA), Jakarta Transactions(JTA) and Jakarta RESTful Web Services(JAX-RS).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Servlet is a Java object that can handle a web request on a particular path and can give a dynamic response to it. An instance of a &lt;code&gt;jakarta.servlet.Servlet&lt;/code&gt; implementation, this object is registered to a Java-based web server (more to come about it) together with the path it wants to handle. Say you’re developing a banking app, and you want the path &lt;code&gt;/balance&lt;/code&gt; to return the balance of the user, you’d do the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Define a class say &lt;code&gt;Balance&lt;/code&gt; that implements &lt;code&gt;jakarta.servlet.Servlet&lt;/code&gt; interface, the class should handle all the business logic related to the user’s balance.&lt;/li&gt;
&lt;li&gt;  Register the &lt;code&gt;Balance&lt;/code&gt; class and the path &lt;code&gt;/balance&lt;/code&gt; to the Web server.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Whenever a client sends a request to the &lt;code&gt;/balance&lt;/code&gt; path, the web server will handle that request to the instance of the &lt;code&gt;Balance&lt;/code&gt; class.&lt;/p&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;A servlet is the basic building block unit of a Jakarta EE web application. As simple as Servlets seem to be, they’re the foundation of Java Web technologies everything else is based on them, technologies like JSP, JSF, Spring MVC, and many more wouldn’t exist without servlets. Non-web technologies like JTA and JPA do not depend on servlets&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;Each of these perspectives helps paint a clearer picture of servlets and &lt;strong&gt;brings&lt;/strong&gt; us closer to understanding Java web technology. Before we get into the specifics of the Servlet API lets us first clarify an important concept, a term that most of us probably have heard it before &lt;strong&gt;Servlet container&lt;/strong&gt;, an important component of Jakarta EE ecosystem that a servlet object lives in.&lt;/p&gt;

&lt;h1&gt;
  
  
  Servlet Container
&lt;/h1&gt;

&lt;p&gt;Spring Boot is incredibly popular for simplifying Java web application development. However, one of the trade-offs of this simplicity is that it often obscures the foundational components of Java web technology. This can make it easy for new developers to feel confident, but when issues arise that require understanding of how things work under the hood, the challenge becomes clear. One such component that Spring Boot abstracts away is the servlet container. If you’ve never heard of servlet containers, or if they’re a mystery to you, this section is for you as I’ll do my best to demystify them.  A servlet container like Apache Tomcat and Eclipse Jetty, is a Java program, like any other Java program, an example of which the infamous "Hello World" program, it starts by invoking the main method and runs inside the JVM.&lt;br&gt;&lt;br&gt;
What makes the Servlet container a bit more special java program is that it provides the running environment and manages servlets, and it achieves this by doing at least the following things&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Instantiate an instance of your Servlet implementation&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Providing Servlet and JSP APIs at runtime&lt;/em&gt;&lt;/strong&gt;: that’s why you don’t package your application with these APIs.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Listening for HTTP requests&lt;/em&gt;&lt;/strong&gt; from a port of your choice by default, both Tomcat and Jetty listen to port 8080.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Parsing HTTP requests&lt;/em&gt;&lt;/strong&gt;: Unmarshalling an HTTP request(plain text) into Java objects representing HTTP requests and responses, as HTTP is a plain text protocol.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Invoking servlet object&lt;/em&gt;&lt;/strong&gt;: The servlet container will spawn a thread(or using an existing one from a pool) to invoke the servlet object that matches the HTTP path and pass the corresponding Java HTTP object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Format and return the response&lt;/em&gt;&lt;/strong&gt;: Marshalling the Java object representing the HTTP response into plain text HTTP response ready for the client to receive it.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When you think about it, a servlet container is an HTTP server, think of it as a minified Java based HTTP server. Emphasis on minified, because servlet containers know only how to run servlets and JSPs unlike full-blown application servers like Glassfish and Weblogic that support full spectrum Jakarta EE specifications like EJB, JTA, and CDI.  &lt;/p&gt;

&lt;p&gt;Multiple web applications can run in the same servlet container as long as they’re installed in different URL workspaces. In our Banking system example, we can have two web applications the customer application, installed at &lt;code&gt;/customer&lt;/code&gt; that handles all customer requests and the back office application, installed at &lt;code&gt;/back_office&lt;/code&gt; that handle requests from the Bank’s employees these two applications will be exposed at &lt;code&gt;mybankdomain.com:port/customer&lt;/code&gt; and &lt;code&gt;mybankdomain.com:port/back_office&lt;/code&gt; respectively. At the end of this article, we talk about how to register Servlets and other components with the container&lt;/p&gt;


&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw40jjt0uc5notmhg8cmw.png" alt="Servlet Container" width="800" height="295"&gt;Servlet Container


&lt;h1&gt;
  
  
  Servlet API
&lt;/h1&gt;

&lt;p&gt;Apart from Servlets themselves, other important building blocks in servlet-powered applications are Listeners and Filters. Listeners are objects that are registered to listen to container events, and the container will notify them whenever such events happen while Filters are components that are meant to pre-process servlet requests and post-process servlet response. In this section, we will also see another two components that play a crucial role in &lt;em&gt;DispatcherServlet&lt;/em&gt;, that is &lt;code&gt;ServletContext&lt;/code&gt; and &lt;code&gt;ServletContainerInitializer&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Servlet
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;📌 NOTE&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;Usages for these methods are demonstrated in the &lt;code&gt;BalanceGenericServlet&lt;/code&gt; class&lt;/em&gt;&lt;/span&gt; &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;jakarta.servlet.Servlet&lt;/code&gt; is a protocol-independent interface that defines minimal specification for a servlet. The interface defines three life-cycle methods that are invoked by the &lt;strong&gt;&lt;em&gt;Servlet Container&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;
  
  
  Servlet Lifecycle:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;init(ServletConfig servletConfig)&lt;/code&gt;: The initializing method It is called by the Servlet container just after the Servlet instance has been constructed, a &lt;code&gt;ServletConfig&lt;/code&gt; is passed to the servlet by the Servlet Container via this method, &lt;code&gt;ServletConfig&lt;/code&gt; is servlet configuration object that contains values like servlet name, servlet initial parameters. This method is the place where the Servlet Container notifies the servlet that is being put into service(for handling request)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;service(ServletRequest req, ServletResponse res)&lt;/code&gt;: We have already mentioned that the servlet container will call the corresponding servlet for each request from the client This is the method that the Servlet container calls, and the request from the client is parsed in to &lt;code&gt;jakarta.servlet.ServletRequest&lt;/code&gt; object and passed through this method.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;destroy()&lt;/code&gt;: The cleanup method, when the Servlet object is done being used, it is taken out of service then get destroyed by calling its &lt;code&gt;destroy()&lt;/code&gt; method before being eligible to Garbage Collector(GC). The Logic to clean up any resource that the servlet possesses should be placed in this method  &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The interface also define the &lt;code&gt;ServletConfig getServletConfig()&lt;/code&gt; method which returns a &lt;code&gt;ServletConfig&lt;/code&gt; which the servlet can use to get the start-up info and the &lt;code&gt;String getServletInfo()&lt;/code&gt; method that the servlet can use to get information about itself like &lt;em&gt;version&lt;/em&gt;, &lt;em&gt;author&lt;/em&gt; and &lt;em&gt;copyright&lt;/em&gt;&lt;/p&gt;


&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F19ohrboj7qyqw5r4uqpz.png" alt="Servlet Life Cycle" width="800" height="259"&gt;Servlet Life-Cycle


&lt;h3&gt;
  
  
  Servlet In Action: Handling Account Balance Requests
&lt;/h3&gt;

&lt;p&gt;We will implement a simple servlet,&lt;code&gt;BalanceGenericServlet&lt;/code&gt;, that handles an HTTP GET request on the &lt;code&gt;/balance&lt;/code&gt; URL pattern and returns random integer value as the balance.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;BalanceGenericServlet.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;
        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;service&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ServletRequest&lt;/span&gt; &lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ServletResponse&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="kd"&gt;throws&lt;/span&gt; &lt;span class="nc"&gt;ServletException&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;IOException&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;info&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MessageFormat&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;format&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Servlet Request is {0}\n"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(!(&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;HttpServletRequest&lt;/span&gt; &lt;span class="n"&gt;httpReq&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;HttpServletResponse&lt;/span&gt; &lt;span class="n"&gt;httpRes&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;ServletException&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"I can only handle Http requests"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;httpReq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getMethod&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"GET"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;httpRes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setStatus&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                &lt;span class="n"&gt;httpRes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setContentType&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"text/plain"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PrintWriter&lt;/span&gt; &lt;span class="n"&gt;writer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;httpRes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getWriter&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                    &lt;span class="n"&gt;writer&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MessageFormat&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;format&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Your balance is {0}"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Random&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;nextInt&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;));&lt;/span&gt;
                &lt;span class="o"&gt;}&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="n"&gt;httpRes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sendError&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"http.method_not_supported"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;service&lt;/code&gt; method first makes sure that the incoming request is an HTTP request by checking the type of &lt;code&gt;ServletRequest&lt;/code&gt; and &lt;code&gt;ServletResponse&lt;/code&gt;. Throws an &lt;code&gt;Exception&lt;/code&gt; if the request is not an HTTP request, remembers &lt;code&gt;jakarta.servlet.Servlet&lt;/code&gt; is protocol-independent, which means even non-HTTP requests will be passed to the servlet. It then goes on to handle the GET request.&lt;/p&gt;

&lt;h3&gt;
  
  
  Simpler Servlet For HTTP Requests:
&lt;/h3&gt;

&lt;p&gt;You probably think "that is a lot of work to handle a simple GET request." You’re right, you almost have no reason to override the &lt;code&gt;serivce&lt;/code&gt; method, the Servlet API comes with two abstract implementations of the &lt;code&gt;Servlet&lt;/code&gt; interface that make you job simpler, the protocol-independent class &lt;code&gt;jakarta.servlet.GenericServlet&lt;/code&gt; and its subclass &lt;code&gt;jakarta.servlet.HttpServlet&lt;/code&gt;, the two classes together do the following&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;GenericServlet&lt;/code&gt;: Provides the no-argument, simpler overloaded version the &lt;code&gt;init(ServletConfig servletConfig)&lt;/code&gt; method.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;HttpServlet&lt;/code&gt;: Should be the superclass for all HTTP servlets, it defines HTTP-specific methods in the form of &lt;code&gt;doXXX()&lt;/code&gt; where &lt;code&gt;XXX&lt;/code&gt; is the HTTP verb the method handles, e.g &lt;code&gt;doGet()&lt;/code&gt;, &lt;code&gt;doPost()&lt;/code&gt;, &lt;code&gt;doPut()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;📌 Warning&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;Remember the Servlet Container does not call the individual Http-specific methods, it calls the &lt;code&gt;service()&lt;/code&gt; method.&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By extending the &lt;code&gt;HttpServlet&lt;/code&gt;, writing HTTP servlets becomes way simpler. You don’t need to implement all the methods from the &lt;code&gt;Servlet&lt;/code&gt; interface and all you have to do is overriding the corresponding HTTP method. We can now handle the &lt;code&gt;/balance&lt;/code&gt; GET request as&lt;/p&gt;

&lt;p&gt;&lt;code&gt;BalanceHttpServlet.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;
        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;doGet&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;HttpServletRequest&lt;/span&gt; &lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;HttpServletResponse&lt;/span&gt; &lt;span class="n"&gt;resp&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="kd"&gt;throws&lt;/span&gt; &lt;span class="nc"&gt;IOException&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;resp&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setStatus&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;resp&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setContentType&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"text/plain"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PrintWriter&lt;/span&gt; &lt;span class="n"&gt;writer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;httpRes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getWriter&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                    &lt;span class="n"&gt;writer&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MessageFormat&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;format&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Your balance is {0}"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Random&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;nextInt&lt;/span&gt;&lt;span class="o"&gt;()));&lt;/span&gt;
                &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can compare our two classes &lt;code&gt;servlet_basics.BalanceGenericServlet&lt;/code&gt; and &lt;code&gt;servlet_basics.BalanceHttpServlet&lt;/code&gt; to observe the differences&lt;/p&gt;

&lt;h2&gt;
  
  
  Filters
&lt;/h2&gt;

&lt;p&gt;By default, servlet containers handle some aspects of requests and responses, such as setting cookies, managing sessions, and interpreting headers. However, this default behavior is not always sufficient. You may need to address cross-cutting concerns like authentication, logging, or request/response encryption. Filters provide a way to intercept requests and responses for pre-processing or post-processing tasks, and they can be applied to specific servlets or URL patterns.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq8by57mbhkerkfa2ev37.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq8by57mbhkerkfa2ev37.png" alt="Filters" width="800" height="217"&gt;&lt;/a&gt;&lt;/p&gt;
Filters



&lt;h3&gt;
  
  
  When to Use Filters:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Use filters for common concerns across multiple servlets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Avoid filters for concerns specific to a single servlet; place such logic directly in the servlet.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Filter Lifecycle:
&lt;/h3&gt;

&lt;p&gt;Filters follow a well-defined lifecycle managed by the servlet container. If filters are registered correctly and successfully, the Servlet Container will invoke the three methods defined in the &lt;code&gt;jakarta.servlet.Filter&lt;/code&gt; interface in this order&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;init(FilterConfig filterConfig)&lt;/code&gt;: This is the place where the Servlet Container is notifying the filter that it is about to be placed in service. This method must complete successfully in order for the &lt;code&gt;doFilter&lt;/code&gt; method to be invoked. A &lt;code&gt;FilterConfig&lt;/code&gt; instance is passed to this method, implementations can opt to save this instance in a field, so information like the filter’s name, filter’s initial parameters can be obtained from it. The &lt;code&gt;FilterConfig&lt;/code&gt; class also contains the &lt;code&gt;getServletContext&lt;/code&gt; method which returns reference to &lt;code&gt;ServletContext&lt;/code&gt; instance&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;doFilter()&lt;/code&gt;: This method is invoked for each request whenever the URL matches the url-pattern or the servlet names specified in the filter definition. The method is invoked before the request reaches the servlet. Instances of &lt;code&gt;ServletRequest&lt;/code&gt; and &lt;code&gt;ServletResponse&lt;/code&gt; are passed to this method, as well as an instance of &lt;code&gt;FilterChain&lt;/code&gt; whose method &lt;code&gt;doFilter&lt;/code&gt; must be called to propagate the call to the next filter in the chain. Remember this method will be invoked only if the &lt;code&gt;init&lt;/code&gt; method is completed successfully, there is the &lt;strong&gt;&lt;em&gt;happens before relationship&lt;/em&gt;&lt;/strong&gt; between this method and the &lt;code&gt;init&lt;/code&gt; method&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;destroy()&lt;/code&gt;: Is invoked after the filter has been taken out of service and before is eligible to the Garbage Collector, this method is called only once and the &lt;code&gt;doFilter&lt;/code&gt; method of this instance is not called anymore after this method has been called. This method is called once all threads have exited the &lt;code&gt;doFilter&lt;/code&gt; method.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Important to note that the &lt;code&gt;init&lt;/code&gt; and &lt;code&gt;destroy&lt;/code&gt; methods are called only once for each filter instance. Also, just like with &lt;code&gt;Servlet&lt;/code&gt; there are two abstract implementations of the &lt;code&gt;Filter&lt;/code&gt; interface &lt;code&gt;GenericFilter&lt;/code&gt; and &lt;code&gt;HttpFilter&lt;/code&gt;, for all HTTP-based filters should implement the &lt;code&gt;HttpFilter&lt;/code&gt; class.  &lt;/p&gt;

&lt;h3&gt;
  
  
  Example: Securing the &lt;code&gt;/balance&lt;/code&gt; Path
&lt;/h3&gt;

&lt;p&gt;Let us leverage filters to secure the path &lt;code&gt;/balance&lt;/code&gt; with HTTP basic authentication, to do that we need a filter that would intercept the URL patterns &lt;code&gt;/balance&lt;/code&gt;, say &lt;code&gt;AuthenticationFilter&lt;/code&gt; and override the &lt;code&gt;doFilter&lt;/code&gt;. The &lt;code&gt;AuthenticationFilter&lt;/code&gt; must be registered to the Servlet Container that it wants to intercept any request that matches the &lt;code&gt;/balance&lt;/code&gt; URL pattern, see the Registering Components with the Servlet Container section.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;AuthenticationFilter.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;doFilter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;HttpServletRequest&lt;/span&gt; &lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;HttpServletResponse&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;FilterChain&lt;/span&gt; &lt;span class="n"&gt;chain&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; 
&lt;span class="kd"&gt;throws&lt;/span&gt; &lt;span class="nc"&gt;IOException&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ServletException&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;authenticationHeader&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getHeader&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Authorization"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;authenticationHeader&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sendError&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;HttpServletResponse&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SC_BAD_REQUEST&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Authorization Header must be supplied"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(!&lt;/span&gt;&lt;span class="n"&gt;authenticationHeader&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;startsWith&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Basic "&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sendError&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;HttpServletResponse&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SC_BAD_REQUEST&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Only Basic Authorization is supported"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;
            &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;credentials&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;authenticationHeader&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;substring&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;split&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;":"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;credentials&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;].&lt;/span&gt;&lt;span class="na"&gt;equalsIgnoreCase&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"user"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;credentials&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;].&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"password"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;chain&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;doFilter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sendError&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;HttpServletResponse&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SC_UNAUTHORIZED&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Wrong username/password combination"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;📌 Warning&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;This is an oversimplified example of how to implement an authentication filter. It assumes the credentials are submitted as plain text, but Base64 decoding is the standard for Basic Authentication. For a production-grade implementation, ensure proper decoding and secure credential handling.&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;The path &lt;code&gt;/balance&lt;/code&gt; is now secured, every HTTP request must contain the &lt;code&gt;Authorization&lt;/code&gt; header with the value &lt;code&gt;Basic user:password&lt;/code&gt; otherwise it will be rejected by the filter.  A Spring developer should have a clear understanding of filters as they’re extensively used in Spring MVC and Spring Security, in fact Spring Security has a filter with the same name as ours &lt;code&gt;AuthenticationFilter&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  ServletContext
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;jakarta.servlet.ServletContext&lt;/code&gt; is an interface for your web application to interact with the servlet container. It acts as a communication bridge between your application and the container, offering functionality such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Retrieving container-specific information, like the supported Servlet API version or the context path of your web application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Dynamically registering servlets, filters, and listeners during application startup.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Providing a shared storage area for servlets, filters, and listeners via context attributes (key-value pairs).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  Context Path
&lt;/h3&gt;

&lt;p&gt;The context path is the portion of the URL that uniquely identifies a web application in the container. From our example in the Servlet Container section the value for context paths will be &lt;code&gt;cutomer&lt;/code&gt; and &lt;code&gt;back_office&lt;/code&gt; respectively. Each application deployed in a servlet container has its own context path.&lt;/p&gt;
&lt;h3&gt;
  
  
  Dynamic Component Registration
&lt;/h3&gt;

&lt;p&gt;Since Servlet 3.0, &lt;code&gt;ServletContext&lt;/code&gt; provides methods like &lt;code&gt;addServlet&lt;/code&gt; and &lt;code&gt;addFilter&lt;/code&gt; for programmatically adding components during startup. This allows more flexible and dynamic configurations compared to static configurations in &lt;code&gt;web.xml&lt;/code&gt; or annotations.&lt;/p&gt;
&lt;h3&gt;
  
  
  Global Application Storage
&lt;/h3&gt;

&lt;p&gt;ServletContext attributes serve as a global storage for your web application, accessible to all servlets, filters, and listeners within the same context. For example, you can store shared configuration data or application state:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;    &lt;span class="n"&gt;servletContext&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setAttribute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"config"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;configObject&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="nc"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;servletContext&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getAttribute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"config"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In distributed web applications (marked as "distributed" in &lt;code&gt;web.xml&lt;/code&gt;), each JVM maintains its own ServletContext. Here &lt;code&gt;ServletContext&lt;/code&gt; shouldn’t be used as the application state as the data in the context isn’t really global.  &lt;/p&gt;

&lt;p&gt;Unlike servlets or filters, ServletContext is not something you’ll frequently use in day-to-day development. However, it plays a vital role in bridging your application with the servlet container and enabling advanced features. We will see &lt;code&gt;ServletContext&lt;/code&gt; demo in conjunction with the &lt;code&gt;ServletContainerInitializer&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F98rxeto5x6l7jxp5qv6n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F98rxeto5x6l7jxp5qv6n.png" alt="Servlet Context" width="800" height="434"&gt;&lt;/a&gt;&lt;/p&gt;
Servlet Context



&lt;h2&gt;
  
  
  Listeners
&lt;/h2&gt;

&lt;p&gt;The Servlet specification allows developers to track key events in a servlet application’s lifecycle and respond to them through listeners. Listeners are components that listen for events in the web application’s lifecycle and act accordingly. When registered, the servlet container invokes the corresponding listener methods in response to specific events.&lt;/p&gt;

&lt;p&gt;Listeners operate at three levels in a servlet application:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Servlet Context-Level (Application-Level): Events involving the state or resources of the application-wide &lt;code&gt;ServletContext&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Session-Level: Events tied to individual user sessions (&lt;code&gt;HttpSession&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Request-Level: Events tied to individual requests (&lt;code&gt;ServletRequest&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Each level supports two event categories:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Lifecycle Changes: Involve events when resources are initialized or destroyed, e.g.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;ServletContextListener&lt;/code&gt;: For &lt;code&gt;ServletContext&lt;/code&gt; initialization and destruction events. &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;HttpSessionListener&lt;/code&gt;: For Http Session creation and destruction.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;ServletRequestListener&lt;/code&gt;: For servlet request creation and destruction.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Attribute Changes: Events triggered by changes to attributes within these resources. Examples include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;ServletContextAttributeListener&lt;/code&gt;: For attribute additions, removals, or replacements in &lt;code&gt;ServletContext&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;HttpSessionAttributeListener&lt;/code&gt;: For similar changes in &lt;code&gt;HttpSession&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Practical Example: Managing User Data with &lt;code&gt;HttpSessionListener&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;Going back to our banking system, say we want to improve the experience of customer users by having their personal data managed in a session so the data is available throughout the session’s lifetime. We can leverage &lt;code&gt;HttpSessionListener&lt;/code&gt; by overriding the &lt;code&gt;sessionCreated&lt;/code&gt; method, the servlet container will notify us through this method when a new session is created, below code gives us the idea how we would approach this&lt;/p&gt;

&lt;p&gt;&lt;code&gt;UserDataLoader.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;sessionCreated&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;HttpSessionEvent&lt;/span&gt; &lt;span class="n"&gt;se&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;HttpSession&lt;/span&gt; &lt;span class="n"&gt;session&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;se&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getSession&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="nc"&gt;UserData&lt;/span&gt; &lt;span class="n"&gt;userData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;getUserData&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="c1"&gt;// Retrieve user data from a database or service&lt;/span&gt;
            &lt;span class="n"&gt;session&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setAttribute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"userData"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;userData&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; 
        &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;📌 Note&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;The getUserData() method represents the logic to fetch user data, typically from a database or external service&lt;/em&gt;&lt;/span&gt;.&lt;/p&gt;

&lt;p&gt;Another example that logs &lt;code&gt;ServletContext&lt;/code&gt; attributes after the &lt;code&gt;ServletContext&lt;/code&gt; has been initialized is demonstrated in the &lt;code&gt;ServletContextLogger&lt;/code&gt; class.&lt;/p&gt;
&lt;h2&gt;
  
  
  ServletContainerInitializer
&lt;/h2&gt;

&lt;p&gt;The last interface we’ll explore is &lt;code&gt;ServletContainerInitializer&lt;/code&gt;. This interface allows third-party libraries to be notified during the web application startup phase through its &lt;code&gt;onStartup&lt;/code&gt; method. Using this method, libraries can programmatically register servlets, filters, and listeners.&lt;/p&gt;


&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcsoa7tuvzi54j267ykyg.png" alt="ServletContainerInitializer" width="800" height="290"&gt;ServletContainerInitializer


&lt;h3&gt;
  
  
  How Does It Work?
&lt;/h3&gt;

&lt;p&gt;The servlet container discovers implementations of ServletContainerInitializer using the META-INF/services mechanism. Specifically, a file named &lt;code&gt;jakarta.servlet.ServletContainerInitializer&lt;/code&gt; in the &lt;code&gt;META-INF/services&lt;/code&gt; directory of a JAR contains the fully qualified name of the initializer class. During startup, the container invokes the &lt;code&gt;onStartup&lt;/code&gt; method of the discovered implementations.&lt;/p&gt;
&lt;h3&gt;
  
  
  Practical Example: Centralized Security
&lt;/h3&gt;

&lt;p&gt;Consider a microservices-based of our banking system requiring extra layered security. For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;In the &lt;code&gt;back_office&lt;/code&gt; service, all endpoints under &lt;code&gt;/admin&lt;/code&gt; should only be accessible to users with the &lt;code&gt;ADMIN&lt;/code&gt; authority.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the &lt;code&gt;customer&lt;/code&gt; service, all endpoints under &lt;code&gt;/transactions&lt;/code&gt; should require re-authentication.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A centralized security configuration can be implemented as a JAR containing a ServletContainerInitializer. The initializer uses a servlet context attribute (&lt;code&gt;serviceName&lt;/code&gt;) to determine the service and register appropriate security filters. Here’s how this might look:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SecurityFilterInitializer.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;onStartup&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Set&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Class&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;?&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;clazzes&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ServletContext&lt;/span&gt; &lt;span class="n"&gt;ctx&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;serviceName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ctx&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getAttribute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"serviceName"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;serviceName&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"back_office"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="n"&gt;registerAdminFilter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ctx&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;serviceName&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"customer"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="n"&gt;registerTransactionFilter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ctx&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;📌 Note&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;The &lt;code&gt;serviceName&lt;/code&gt; attribute is set in the servlet context before deployment through &lt;code&gt;web.xml&lt;/code&gt;. Check the class &lt;code&gt;SecurityFilterInitializer&lt;/code&gt; for the full implementations. Depending on the value of the &lt;code&gt;serviceName&lt;/code&gt; you can send an HTTP request that starts with either &lt;code&gt;/transactions&lt;/code&gt; or &lt;code&gt;/admin&lt;/code&gt; paths to see the filters in action.&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  The Role of &lt;code&gt;@HandlesTypes&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;An implementation of &lt;code&gt;ServletContainerInitializer&lt;/code&gt; can be annotated with &lt;code&gt;@HandlesTypes.&lt;/code&gt; This annotation specifies class types (interfaces or abstract classes) the initializer can handle. The container will pass implementations or subclasses of these types as the first argument to the &lt;code&gt;onStartup&lt;/code&gt; method. This mechanism is particularly useful for frameworks like Spring, which uses &lt;code&gt;SpringServletContainerInitializer&lt;/code&gt; to delegate servlet context initialization to programmer-defined classes implementing &lt;code&gt;WebApplicationInitializer&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;📌 Note&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;If this is still somehow confusing, Check our &lt;code&gt;SecurityFilterInitializer&lt;/code&gt; and &lt;code&gt;OtherSecurityInitializer&lt;/code&gt; and their Javadoc to see the whole thing in action.&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;In the next part of this series, we’ll explore how Spring MVC leverages &lt;code&gt;ServletContainerInitializer&lt;/code&gt; and the &lt;code&gt;@HandlesTypes&lt;/code&gt; annotation to register the &lt;code&gt;DispatcherServlet&lt;/code&gt; programmatically.&lt;/p&gt;
&lt;h1&gt;
  
  
  Registering Components with the Servlet Container
&lt;/h1&gt;

&lt;p&gt;When working with servlets, filters, and listeners, you need to inform the servlet container about their existence and how they should be used. This process is called component registration. Servlet containers provide two main ways to register these components:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Declarative Registration (&lt;code&gt;web.xml&lt;/code&gt; Deployment Descriptor): The traditional way of registering servlets, filters, and listeners, is by defining them in the web.xml file. This XML file resides in the &lt;code&gt;WEB-INF&lt;/code&gt; directory of your web application. For example:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;web.xml&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight xml"&gt;&lt;code&gt;    &lt;span class="c"&gt;&amp;lt;!-- Registering a Servlet --&amp;gt;&lt;/span&gt;
    &lt;span class="c"&gt;&amp;lt;!-- xmlns declaration removed for brevity--&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;web-app&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;servlet&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;servlet-name&amp;gt;&lt;/span&gt;BalanceGenericServlet&lt;span class="nt"&gt;&amp;lt;/servlet-name&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;servlet-class&amp;gt;&lt;/span&gt;servlet_basics.BalanceGenericServlet&lt;span class="nt"&gt;&amp;lt;/servlet-class&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/servlet&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;servlet-mapping&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;servlet-name&amp;gt;&lt;/span&gt;BalanceServlet&lt;span class="nt"&gt;&amp;lt;/servlet-name&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;url-pattern&amp;gt;&lt;/span&gt;/balance&lt;span class="nt"&gt;&amp;lt;/url-pattern&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/servlet-mapping&amp;gt;&lt;/span&gt;

    &lt;span class="c"&gt;&amp;lt;!-- Registering a Filter --&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;filter&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;filter-name&amp;gt;&lt;/span&gt;AuthenticationFilter&lt;span class="nt"&gt;&amp;lt;/filter-name&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;filter-class&amp;gt;&lt;/span&gt;servlet_basics.AuthenticationFilter&lt;span class="nt"&gt;&amp;lt;/filter-class&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/filter&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;filter-mapping&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;filter-name&amp;gt;&lt;/span&gt;AuthenticationFilter&lt;span class="nt"&gt;&amp;lt;/filter-name&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;url-pattern&amp;gt;&lt;/span&gt;/balance&lt;span class="nt"&gt;&amp;lt;/url-pattern&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/filter-mapping&amp;gt;&lt;/span&gt;

    &lt;span class="c"&gt;&amp;lt;!-- Registering a Listener --&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;listener&amp;gt;&lt;/span&gt;
        &lt;span class="nt"&gt;&amp;lt;listener-class&amp;gt;&lt;/span&gt;servlet_basics.UserDataLoader &lt;span class="nt"&gt;&amp;lt;/listener-class&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/listener&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;/web-app&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;




&lt;/li&gt;

&lt;li&gt;&lt;p&gt;Programmatic Registration (Annotations): Since Servlet 3.0, you can use annotations to register components directly in the source code, simplifying the process and avoiding the need for a &lt;code&gt;web.xml&lt;/code&gt; file.&lt;/p&gt;&lt;/li&gt;

&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Servlet Registration:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;BalanceGenericServlet.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;
    &lt;span class="nd"&gt;@WebServlet&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Balance"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;urlPatterns&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;&lt;span class="s"&gt;"/balance"&lt;/span&gt;&lt;span class="o"&gt;})&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BalanceGenericServlet&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;Servlet&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Implementation&lt;/span&gt;

 &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Filter Registration:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;AuthenticationFilter.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;
    &lt;span class="nd"&gt;@WebFilter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;filterName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"AuthenticationFilter"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;urlPatterns&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;&lt;span class="s"&gt;"/balance"&lt;/span&gt;&lt;span class="o"&gt;})&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AuthenticationFilter&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;HttpFilter&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Implementation&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Listener Registration:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;UserDataLoader.java&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;
   &lt;span class="nd"&gt;@WebListener&lt;/span&gt;
   &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserDataLoader&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;HttpSessionListener&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// Implementation&lt;/span&gt;
 &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both methods achieve the same outcome but serve different needs. Use &lt;code&gt;web.xml&lt;/code&gt; when you require centralized configuration and annotations for a more modern, streamlined approach.&lt;/p&gt;

&lt;p&gt;By registering your components correctly, the servlet container knows how to manage them and route requests effectively within your application.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;In this first part of our series, we explored the foundational concepts of servlet technology. We discussed servlets, filters, listeners, servlet containers, and how these building blocks work together to create robust Java web applications. However, we haven’t touched on everything there is to know about the servlet technology. Our focus has been on aspects most relevant to understanding how Spring MVC’s is bootstrapped and how &lt;code&gt;DispatcherServlet&lt;/code&gt; works.&lt;/p&gt;

&lt;p&gt;If you’re eager to deepen your knowledge, we encourage you to explore the Servlet Specification and Jakarta EE further, as it offers many features and possibilities beyond what we’ve covered here.&lt;/p&gt;

&lt;p&gt;In the next part of this series, we’ll dive into how Spring leverages the servlet ecosystem to bootstrap Spring MVC and make its &lt;code&gt;DispatcherServlet&lt;/code&gt; a powerful front controller.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Please like and follow for more incoming Java/Spring contents&lt;/em&gt;.&lt;br&gt;
&lt;em&gt;Leave comments for questions or any further clarification&lt;/em&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>spring</category>
      <category>springboot</category>
      <category>web</category>
    </item>
    <item>
      <title>Java Cleaners: The Modern Way to Manage External Resources</title>
      <dc:creator>Ahmed Jaad</dc:creator>
      <pubDate>Tue, 13 Aug 2024 20:49:21 +0000</pubDate>
      <link>https://dev.to/ahmedjaad/java-cleaners-the-modern-way-to-manage-external-resources-4d4</link>
      <guid>https://dev.to/ahmedjaad/java-cleaners-the-modern-way-to-manage-external-resources-4d4</guid>
      <description>&lt;p&gt;This article is accompanied by source code on &lt;a href="https://github.com/ahmedjaadi/java-cleaners.git" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;. Following along with the code, while reading will help you better understand the concepts discussed.&lt;br&gt;
If you’re the type of programmer who likes to understand the internals of how things work before seeing examples, you can jump directly to Cleaners behind the scene after the introduction.&lt;/p&gt;



&lt;ul&gt;
&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;Simple Cleaner in action&lt;/li&gt;
&lt;li&gt;Cleaners, the right way&lt;/li&gt;
&lt;li&gt;Cleaners, the effective way&lt;/li&gt;
&lt;li&gt;Cleaners behind the scene&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Think of a scenario where you have an object that holds references to external resources (files, sockets, and so on). And you want to have control over how these resources are released once the holding object is no longer active/accessible, how do you achieve that in Java?. Prior to Java 9 programmers could use a finalizer by overriding the &lt;code&gt;Object&lt;/code&gt;’s class &lt;code&gt;finalize()&lt;/code&gt; method. Finalizers have many disadvantages, including being slow, unreliable and dangerous. It is one of those features that are hated by both those who implement the JDK and those who use it.&lt;/p&gt;

&lt;p&gt;Since Java 9, Finalizers have been deprecated and programmers have a better option to achieve this in Cleaners, Cleaners provide a better way to manage and handle cleaning/finalizing actions. Cleaners work in a pattern where they let resource holding objects register themselves and their corresponding cleaning actions. And then Cleaners will call the cleaning actions once these objects are not accessible by the application code. &lt;br&gt;
This is not the article to tell you why Cleaners are better than Finalizers, though I will briefly list some of their differences.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Finalizers Vs Cleaners&lt;/strong&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Finalizers&lt;/th&gt;
&lt;th&gt;Cleaners&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Finalizers are invoked by one of Garbage Collector’s threads, you as a programmer don’t have control over what thread will invoke your finalizing logic&lt;/td&gt;
&lt;td&gt;Unlike with finalizers, with Cleaners, programmers can opt to have control over the thread that invokes the cleaning logic.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Finalizing logic is invoked when the object is actually being collected by GC&lt;/td&gt;
&lt;td&gt;Cleaning logic is invoked when the object becomes &lt;strong&gt;&lt;em&gt;Phantom Reachable&lt;/em&gt;&lt;/strong&gt;, that is our application has no means to access it anymore&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Finalizing logic is part of the object holding the resources&lt;/td&gt;
&lt;td&gt;Cleaning logic and its state are encapsulated in a separate object.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;No registration/deregistration mechanism&lt;/td&gt;
&lt;td&gt;Provides means for registering cleaning actions and explicit invocation/deregistration&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;h2&gt;
  
  
  Simple Cleaner in action
&lt;/h2&gt;

&lt;p&gt;Enough chit-chats let us see Cleaners in action.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ResourceHolder&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.lang.ref.Cleaner&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
 &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Cleaner&lt;/span&gt; &lt;span class="no"&gt;CLEANER&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Cleaner&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;create&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;ResourceHolder&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="no"&gt;CLEANER&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;register&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"I'm doing some clean up"&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;...&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt; &lt;span class="n"&gt;resourceHolder&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="n"&gt;resourceHolder&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;gc&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="o"&gt;}}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Few lines of code but a lot is happening here, Let us break it down&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The constant &lt;code&gt;CLEANER&lt;/code&gt; is of type &lt;code&gt;java.lang.ref.Cleaner&lt;/code&gt;, as you can tell from its name,
this is the central and starting point of the Cleaners feature in Java.
The &lt;code&gt;CLEANER&lt;/code&gt; variable is declared as static as it should be, Cleaners should never be instance variables,
they should be shared across different classes as much as possible.&lt;/li&gt;
&lt;li&gt;In the constructor, instances of &lt;code&gt;ResourceHolder&lt;/code&gt; are registering themselves to the Cleaner along with their cleaning action, the cleaning action is a &lt;code&gt;Runnable&lt;/code&gt; job that the Cleaner guarantees to invoke at most once (at most once, meaning it is possible not to run at all).
By calling Cleaner’s &lt;code&gt;register()&lt;/code&gt; method, these instances are basically saying two things to the Cleaner

&lt;ul&gt;
&lt;li&gt;Keep track of me as long as I live&lt;/li&gt;
&lt;li&gt;And once I am no longer active (&lt;strong&gt;&lt;em&gt;Phantom Reachable&lt;/em&gt;&lt;/strong&gt;), please do your best and invoke my cleaning action.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;In the main method we instantiate an object of &lt;code&gt;ResourceHolder&lt;/code&gt; and immediately set its variable to &lt;code&gt;null&lt;/code&gt;, since the object has only one variable reference, our application can no longer access the object, i.e., it has become &lt;strong&gt;&lt;em&gt;Phantom Reachable&lt;/em&gt;&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;We call &lt;code&gt;System.gc()&lt;/code&gt; to request JVM to run the Garbage Collector,
consequentially this will trigger the Cleaner to run the cleaning action.
Typically, you don’t need to call &lt;code&gt;System.gc()&lt;/code&gt; but as simple as our application,
we need to facilitate the Cleaner to run the action&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Run the application, and hopefully you see &lt;code&gt;I’m doing some clean up&lt;/code&gt; somewhere in your standard output.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;🔥 CAUTION&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;We started with the simplest possible way to use Cleaners, so we can demonstrate its usage in a simplified way, bear in mind though this is neither effective nor the right way to use Cleaners&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Cleaners, the right way
&lt;/h2&gt;

&lt;p&gt;Our first example was more than good enough to see Cleaners in action,&lt;br&gt;
but as we warned, it is not the right way to use Cleaners in a real application.&lt;br&gt;
Let’s see what is wrong with what we did.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;We initiated a &lt;code&gt;Cleaner&lt;/code&gt; object as a class member of the &lt;code&gt;ResourceHolder&lt;/code&gt;: As we mentioned earlier Cleaners should be shared across Classes and should not belong to individual classes, reason behind being each Cleaner instance maintains a thread, which is a limited native resource, and you want to be cautious when you consume native resources.&lt;br&gt;
In a real application, we typically get a Cleaner object from a utility or a Singleton class like&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight java"&gt;&lt;code&gt;  &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="no"&gt;CLEANER&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;AppUtil&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getCleaner&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;




&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;We passed in a lambda as our Cleaning action: You should &lt;strong&gt;NEVER&lt;/strong&gt; pass in a lambda as your cleaning action.&lt;br&gt;
To understand why,&lt;br&gt;
let us refactor our previous example by extracting the printed out message and make it an instance variable&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ResourceHolder&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
   &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Cleaner&lt;/span&gt; &lt;span class="no"&gt;CLEANER&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Cleaner&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;create&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
   &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;cleaningMessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"I'm doing some clean up"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
   &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;ResourceHolder&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
       &lt;span class="no"&gt;CLEANER&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;register&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cleaningMessage&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
   &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;Run the application and see what happens.&lt;br&gt;
  I will tell you what happens,&lt;br&gt;
  the cleaning action will never get invoked no    matter how many times you run your application.&lt;br&gt;
  Let us see why&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Internally, Cleaners make use of &lt;code&gt;PhantomReference&lt;/code&gt; and &lt;code&gt;ReferenceQueue&lt;/code&gt; to keep track of registered objects,
once an object becomes &lt;strong&gt;&lt;em&gt;Phantom Reachable&lt;/em&gt;&lt;/strong&gt; the &lt;code&gt;ReferenceQueue&lt;/code&gt;  will notify the Cleaner
and the Cleaner will use its thread to run the corresponding cleaning action.&lt;/li&gt;
&lt;li&gt;By having the lambda accessing the instance member we’re forcing the lambda to hold the &lt;code&gt;this&lt;/code&gt; reference(of &lt;code&gt;ResourceHolder&lt;/code&gt; instance), because of this the object will never ever become &lt;strong&gt;&lt;em&gt;Phantom Reachable&lt;/em&gt;&lt;/strong&gt;
because our Application code still has reference to it.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;📌 NOTE&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;If you still wonder how in our first example, the cleaning action is invoked despite having it as a lambda. The reason is, the lambda in the first example does not access any instance variable, and unlike inner classes, Lambdas won’t implicitly hold the containing object reference unless they’re forced to.&lt;/em&gt;&lt;/span&gt;&lt;br&gt;&lt;br&gt;
The right way is to encapsulate your cleaning action together with the state it needs in a static nested class.&lt;br&gt;&lt;br&gt;
&lt;strong&gt;📌 Warning&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;Don’t use inner class anonymous or not, it is worse than using lambda because an inner class instance would hold a reference to the outer class instance regardless of whether they access their instance variable or not.&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We didn't make use of the return value from the &lt;code&gt;Cleaner.create()&lt;/code&gt;: The &lt;code&gt;create()&lt;/code&gt; actually returns something very important.a &lt;code&gt;Cleanable&lt;/code&gt; object, this object has a &lt;code&gt;clean()&lt;/code&gt; method that wraps your cleaning logic, you as a programmer can opt to do the cleanup yourself by invoking the &lt;code&gt;clean()&lt;/code&gt; method. As mentioned earlier, another thing that makes Cleaners superior to Finalizers is that you can actually deregister your cleaning action. The &lt;code&gt;clean()&lt;/code&gt; method actually deregisters your object first, and then it invokes your cleaning action, this way it guarantees the at-most once behavior.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now let us improve each one of these points and revise our &lt;code&gt;ResourceHolder&lt;/code&gt; class&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ResourceHolder&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.lang.ref.Cleaner&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Cleaner&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Cleanable&lt;/span&gt; &lt;span class="n"&gt;cleanable&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ExternalResource&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;ResourceHolder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ExternalResource&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;cleanable&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;AppUtil&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getCleaner&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;register&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;CleaningAction&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;externalResource&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;//    You can call this method whenever is the right time to release resource&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;releaseResource&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;cleanable&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;clean&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;doSomethingWithResource&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;printf&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Do something cool with the important resource: %s \n"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CleaningAction&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;Runnable&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;ExternalResource&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

        &lt;span class="nc"&gt;CleaningAction&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ExternalResource&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;externalResource&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;

        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
&lt;span class="c1"&gt;//          Cleaning up the important resources&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Doing some cleaning logic here, releasing up very important resource"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;externalResource&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;...&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt; &lt;span class="n"&gt;resourceHolder&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ExternalResource&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="n"&gt;resourceHolder&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;doSomethingWithResource&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="cm"&gt;/*
        After doing some important work, we can explicitly release
        resources/invoke the cleaning action
*/&lt;/span&gt;
        &lt;span class="n"&gt;resourceHolder&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;releaseResource&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="c1"&gt;//      What if we explicitly invoke the cleaning action twice?&lt;/span&gt;
        &lt;span class="n"&gt;resourceHolder&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;releaseResource&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;ExternalResource&lt;/code&gt; is our hypothetical resource that we want to release when we’re done with it.&lt;br&gt;
The cleaning action is now encapsulated in its own class, and we make use of the &lt;code&gt;CleaniangAction&lt;/code&gt; object, we call it’s &lt;code&gt;clean()&lt;/code&gt; method in the &lt;code&gt;releaseResources()&lt;/code&gt; method to do the cleanup ourselves.&lt;br&gt;
As stated earlier, Cleaners guarantee at most one invocation of the cleaning action, and since we call the &lt;code&gt;clean()&lt;/code&gt; method explicitly the Cleaner will not invoke our cleaning action except in the case of a failure like an exception is thrown before the clean method is called, in this case the Cleaner will invoke our cleaning action when the &lt;code&gt;ResourceHolder&lt;/code&gt; object becomes &lt;strong&gt;&lt;em&gt;Phantom Reachable&lt;/em&gt;&lt;/strong&gt;, that is we use the Cleaner as our &lt;strong&gt;&lt;em&gt;safety-net&lt;/em&gt;&lt;/strong&gt;, our backup plan when the first plan to clean our own mess doesn’t work.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;❗ IMPORTANT&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;The behavior of Cleaners during &lt;code&gt;System.exit&lt;/code&gt; is implementation-specific. With this in mind, programmers should always prefer to explicitly invoke the cleaning action over relying on the Cleaners themselves.&lt;/em&gt;&lt;/span&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  Cleaners, the effective way
&lt;/h2&gt;

&lt;p&gt;By now we’ve established the right way to use Cleaners is to explicitly call the cleaning action and rely on them as our backup plan.What if there’s a better way? Where we don’t explicitly call the cleaning action, and the Cleaner stays intact as our &lt;strong&gt;&lt;em&gt;safety-net&lt;/em&gt;&lt;/strong&gt;.&lt;br&gt;
This can be achieved by having the &lt;code&gt;ResourceHolder&lt;/code&gt; class implement the &lt;code&gt;AutoCloseable&lt;/code&gt; interface and place the cleaning action call in the &lt;code&gt;close()&lt;/code&gt; method, our &lt;code&gt;ResourceHolder&lt;/code&gt; can now be used in a &lt;strong&gt;&lt;em&gt;try-with-resources&lt;/em&gt;&lt;/strong&gt; block. The revised  &lt;code&gt;ResourceHolder&lt;/code&gt; should look like below.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ResourceHolder&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.lang.ref.Cleaner.Cleanable&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;AutoCloseable&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ExternalResource&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Cleaner&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Cleanable&lt;/span&gt; &lt;span class="n"&gt;cleanable&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;ResourceHolder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ExternalResource&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;externalResource&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;cleanable&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;AppUtil&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getCleaner&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;register&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;CleaningAction&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;doSomethingWithResource&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;printf&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Do something cool with the important resource: %s \n"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;close&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"cleaning action invoked by the close method"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;cleanable&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;clean&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CleaningAction&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;Runnable&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;ExternalResource&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

        &lt;span class="nc"&gt;CleaningAction&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ExternalResource&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;externalResource&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;externalResource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;

        &lt;span class="nd"&gt;@Override&lt;/span&gt;
        &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
&lt;span class="c1"&gt;//            cleaning up the important resources&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Doing some cleaning logic here, releasing up very important resources"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;externalResource&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
&lt;span class="c1"&gt;//      This is an effective way to use cleaners with instances that hold crucial resources&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ResourceHolder&lt;/span&gt; &lt;span class="n"&gt;resourceHolder&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ExternalResource&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;)))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;resourceHolder&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;doSomethingWithResource&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Goodbye"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="cm"&gt;/*
    In case the client code does not use the try-with-resource as expected,
    the Cleaner will act as the safety-net
*/&lt;/span&gt;
        &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt; &lt;span class="n"&gt;resourceHolder&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ResourceHolder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ExternalResource&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
        &lt;span class="n"&gt;resourceHolder&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;doSomethingWithResource&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;resourceHolder&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;gc&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// to facilitate the running of the cleaning action&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Cleaners behind the scene
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;📌 NOTE&lt;/strong&gt;&lt;br&gt;
&lt;span&gt;&lt;em&gt;To understand more and see how Cleaners work, checkout the &lt;a href="https://github.com/ahmedjaad/understanding-java-cleaners/blob/main/src/main/java/cleaner/our_cleaner/OurCleaner.java" rel="noopener noreferrer"&gt;&lt;code&gt;OurCleaner&lt;/code&gt;&lt;/a&gt; class under the &lt;code&gt;our_cleaner&lt;/code&gt; package that imitates the JDK real implementation of &lt;code&gt;Cleaner&lt;/code&gt;. You can replace the real &lt;code&gt;Cleaner&lt;/code&gt; and &lt;code&gt;Cleanable&lt;/code&gt; with &lt;code&gt;OurCleaner&lt;/code&gt; and &lt;code&gt;OurCleanable&lt;/code&gt; respectively in all of our examples and play with it.&lt;/em&gt;&lt;/span&gt;&lt;br&gt;&lt;br&gt;
Let us first get a clearer picture of a few, already mentioned terms, &lt;strong&gt;&lt;em&gt;phantom-reachable&lt;/em&gt;&lt;/strong&gt;, &lt;code&gt;PhantomReference&lt;/code&gt; and &lt;code&gt;ReferenceQueue&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Consider the following code&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;myObject&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;In the Garbage Collector (GC) world the created instance of &lt;code&gt;Object&lt;/code&gt;  is said to be &lt;strong&gt;&lt;em&gt;strongly-reachable&lt;/em&gt;&lt;/strong&gt;, why? Because it is alive, and in-use i.e., Our application code has a reference to it that is stored in the &lt;code&gt;myObject&lt;/code&gt; variable, assume we don’t set another variable and somewhere in our code this happens&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;myObject&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;The instance is now said to be &lt;strong&gt;&lt;em&gt;unreachable&lt;/em&gt;&lt;/strong&gt;, and is eligible for reclamation by the GC.&lt;br&gt;
Now let us tweak the code a bit&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;myObject&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="nc"&gt;PhantomReference&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;reference&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;PhantomReference&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;(&lt;/span&gt;&lt;span class="n"&gt;myObject&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;code&gt;Reference&lt;/code&gt; is a class provided by JDK to represent reachability of an object during JVM runtime, the object a &lt;code&gt;Reference&lt;/code&gt; object is referring to is known as &lt;code&gt;referent&lt;/code&gt;, &lt;code&gt;PhantomReference&lt;/code&gt; is a type(also an extension) of &lt;code&gt;Reference&lt;/code&gt; whose purpose will be explained below in conjunction with &lt;code&gt;ReferenceQueue&lt;/code&gt;.&lt;br&gt;
Ignore the second parameter of the constructor for now, and again assume somewhere in our code this happens again&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;myObject&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;Now our object is not just &lt;strong&gt;&lt;em&gt;unreachable&lt;/em&gt;&lt;/strong&gt; it is &lt;strong&gt;&lt;em&gt;phantom-reachable&lt;/em&gt;&lt;/strong&gt; because no part of our application code can access it, &lt;strong&gt;AND&lt;/strong&gt; it is a &lt;code&gt;referent&lt;/code&gt; of a &lt;code&gt;PhantomReference&lt;/code&gt; object.  &lt;/p&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;After the GC has finalized a &lt;strong&gt;&lt;em&gt;phantom-reachable&lt;/em&gt;&lt;/strong&gt; object, the GC attaches its &lt;code&gt;PhantomReference&lt;/code&gt; object(not the &lt;code&gt;referent&lt;/code&gt;) to a special kind of queue called &lt;code&gt;ReferenceQueue&lt;/code&gt;. Let us see how these two concepts work together&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;myObject&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="nc"&gt;ReferenceQueue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ReferenceQueue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;
&lt;span class="nc"&gt;PhantomReference&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;reference1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;PhantomReference&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;(&lt;/span&gt;&lt;span class="n"&gt;myObject&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="n"&gt;myObject&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="nc"&gt;PhantomReference&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;reference2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PhantomReference&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;remove&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;We supply a &lt;code&gt;ReferenceQueue&lt;/code&gt; when we create a &lt;code&gt;PhantomReference&lt;/code&gt; object so the GC knows where to attach it when its referent has been finalized. The &lt;code&gt;ReferenceQueue&lt;/code&gt; class provides two methods to poll the queue, &lt;code&gt;remove()&lt;/code&gt;, this will block when the queue is empty until the queue has an element to return, and &lt;code&gt;poll()&lt;/code&gt; this is non-blocking, when the queue is empty it will return &lt;code&gt;null&lt;/code&gt; immediately.&lt;br&gt;
 With that explanation, the code above should be easy to understand, once &lt;code&gt;myObject&lt;/code&gt; becomes &lt;strong&gt;&lt;em&gt;phantom-reachable&lt;/em&gt;&lt;/strong&gt; the GC will attach the &lt;code&gt;PhantomReference&lt;/code&gt; object to &lt;code&gt;queue&lt;/code&gt; and we get it by using the &lt;code&gt;remove()&lt;/code&gt; method, that is to say &lt;code&gt;reference1&lt;/code&gt; and &lt;code&gt;reference2&lt;/code&gt; variables refer to the same object.&lt;/p&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;Now that these concepts are out of the way, let’s explain two Cleaner-specific types&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;For each cleaning action, Cleaner will wrap it in a &lt;code&gt;Cleanable&lt;/code&gt; instance, &lt;code&gt;Cleanable&lt;/code&gt; has one method, &lt;code&gt;clean()&lt;/code&gt;, this method ensure the at-most once invocation behavior before invoking the cleaning action.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;PhantomCleanable&lt;/code&gt; implements &lt;code&gt;Cleanable&lt;/code&gt; and extends &lt;code&gt;PhantomReference&lt;/code&gt;, this class is the Cleaner’s way to associate the referent(resource holder) with their cleaning action&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;From this point on understanding the internals of Cleaner should be straight forward.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cleaner Life-Cycle Overview&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F96dnpxm4logfswy7sglt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F96dnpxm4logfswy7sglt.png" alt="Cleaner Life-Cycle Overview" width="800" height="554"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let us look at the life-cycle of a &lt;code&gt;Cleaner&lt;/code&gt; object&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;The static &lt;code&gt;Cleaner.create()&lt;/code&gt; method instantiates a new &lt;code&gt;Cleaner&lt;/code&gt; but it also does a few other things&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It instantiates a new &lt;code&gt;ReferenceQueue&lt;/code&gt;, that the &lt;code&gt;Cleaner&lt;/code&gt; objet’s thread will be polling&lt;/li&gt;
&lt;li&gt;It creates a doubly linked list of &lt;code&gt;PhantomCleanable&lt;/code&gt; objects,
these objects are associated with the queue created from the previous step.&lt;/li&gt;
&lt;li&gt;It creates a &lt;code&gt;PhantomCleanable&lt;/code&gt; object with itself as the referent and empty cleaning action.&lt;/li&gt;
&lt;li&gt;It starts a daemon thread that will be polling the &lt;code&gt;ReferenceQueue&lt;/code&gt; as long as the doubly linked list is not empty.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By adding itself into the list, the cleaner ensures that its thread runs at least until the cleaner itself becomes unreachable&lt;/p&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;For each &lt;code&gt;Cleaner.register()&lt;/code&gt; call, the cleaner creates an instance of &lt;code&gt;PhantomCleanable&lt;/code&gt; with the resource holder as the referent and the cleaning action will be wrapped in the &lt;code&gt;clean()&lt;/code&gt; method, the object is then added to the aforementioned linked list.&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;The Cleaner’s thread will be polling the queue, and when a &lt;code&gt;PhantomCleanable&lt;/code&gt; is returned by the queue, it will invoke its &lt;code&gt;clean()&lt;/code&gt; method.  Remember the &lt;code&gt;clean()&lt;/code&gt; method only calls the cleaning action if it manages to remove the &lt;code&gt;PhantomCleanable&lt;/code&gt; object from the linked list, if the &lt;code&gt;PhantomCleanable&lt;/code&gt; object is not on the linked list it does nothing&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;The thread will continue to run as long as the linked list is not empty, this will only happen when&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;All the cleaning actions have been invoked, and&lt;/li&gt;
&lt;li&gt;The Cleaner itself has become &lt;strong&gt;&lt;em&gt;phantom-reachable&lt;/em&gt;&lt;/strong&gt; and has been reclaimed by the GC&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Please like and follow for more incoming Java/Spring contents&lt;/em&gt;. &lt;br&gt;
&lt;em&gt;Leave comments for questions or any further clarification&lt;/em&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>coding</category>
      <category>development</category>
    </item>
  </channel>
</rss>
