Showing posts with label Intercepting Filter. Show all posts
Showing posts with label Intercepting Filter. Show all posts

Tuesday, 1 October 2013

Intercepting Filter Design Pattern - KeyPoints

🚀 Master Java Enterprise Architecture!

Subscribe to Ram N Java for clean software design patterns, enterprise Java tutorials, and architecture best practices!

🔔 Subscribe to Ram N Java

What Is the Intercepting Filter Design Pattern?

The Intercepting Filter Design Pattern is an architectural pattern used to intercept incoming HTTP requests and outgoing responses. It enables you to perform pre-processing (such as authentication, authorization, or logging) before a request hits the main target handler, as well as post-processing (such as data compression or encryption) before returning the response to the client.

Key Takeaways & Core Concepts

  • Centralized Pre/Post Processing: Consolidates cross-cutting concerns (logging, debugging, session validation, encryption) into discrete, reusable filter components rather than cluttering business controllers.
  • Loose Coupling & Modularity: The core target application does not know which filters are running. Filters execute independently and can be added, rearranged, or removed dynamically without touching business logic.
  • Chaining Mechanism: Filters are linked sequentially via a FilterChain. Each filter executes its pre-processing task and then passes the request down the chain to the next filter or target.
  • Declarative Configuration: In enterprise web applications (like Java Servlets and Spring MVC), filters can be declared and ordered declaratively through deployment descriptors or annotations.

Primary Components in the Architecture

  1. Filter: An individual unit that performs a specific processing task (e.g., AuthenticationFilter, LoggingFilter).
  2. Filter Chain: An ordered collection of filters that coordinates sequential execution before invoking the target.
  3. Filter Manager: Manages filter creation, lifecycle, and creates the appropriate chain for incoming requests.
  4. Target: The ultimate destination requested by the client (such as a Servlet, Controller, or View).

Real-World Use Cases

  • Security & Authentication: Validating JWT tokens or session cookies before granting access to protected routes.
  • Audit Logging: Recording client IP addresses, timestamps, and request parameters across every endpoint.
  • Data Transformation: Automatically compressing response payloads with GZIP or decrypting encrypted incoming request bodies.

Recommended Next Videos

Continue exploring the Intercepting Filter pattern with these tutorials from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=iPRy1J8Ar1s

Click the below Image to Enlarge

Friday, 30 August 2013

Intercepting Filter Design Pattern - Implementation

🚀 Level Up Your Java Architecture Skills!

Subscribe to Ram N Java for clean code walkthroughs, design pattern implementations, and step-by-step programming guides!

🔔 Subscribe to Ram N Java

Practical Implementation of Intercepting Filter

The Intercepting Filter Design Pattern is widely applied in modern web frameworks and enterprise backends to handle cross-cutting concerns cleanly. Instead of embedding security checks, request encoding, or auditing directly into your business controllers, this pattern lets you execute specialized filters in an ordered chain before reaching the final handler.

How the Components Work Together

  • Filter Interface: Defines a standard contract (such as an execute(String request) method) that every concrete filter implements.
  • Concrete Filters: Specific implementations that handle focused tasks (e.g., an AuthenticationFilter validating credentials or a DebugFilter logging request payloads).
  • Target: The ultimate business destination or resource (such as a core service or web handler) that processes the request once all filters approve.
  • FilterChain: Maintains an ordered list of filters, executes them sequentially, and finally triggers the target.
  • FilterManager: Coordinates the filter chain setup and manages which filters attach to incoming requests.
  • Client: The caller that sends requests through the FilterManager rather than directly to the target.

Execution Flow in Code

  1. The Client issues an incoming request.
  2. The FilterManager receives the request and initializes the FilterChain.
  3. The FilterChain invokes each registered Filter in succession (e.g., checking tokens, validating headers, logging data).
  4. Once every filter executes successfully, the chain passes control directly to the Target.

Key Benefits for Software Design

  • Single Responsibility: Each filter class has only one job, making your codebase modular and easy to debug.
  • Dynamic Extensibility: You can plug in new filters (like rate limiting or data compression) without modifying the target resource.
  • High Reusability: Common filters can be attached to multiple handlers across different services.

Recommended Next Videos

Deepen your understanding of filters and servlet architecture with these related tutorials from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=sWtchigtgXk

Click the below Image to Enlarge
Intercepting Filter Design Pattern - Implementation






















Filter.Java

public interface Filter
{
public void processRequest(String request);
}

AuthenticationFilter.java

public class AuthenticationFilter implements Filter
{

@Override
        public void processRequest( String request )
        {
System.out.println("Authenticating the request by AuthenticationFilter : " + request);
       
        }

}

LoggingFilter.java

public class LoggingFilter implements Filter
{
@Override
        public void processRequest( String request )
        {
System.out.println("Request Tracking is done by LoggingFilter : " + request);        
        }
}

Target.java

public class Target
{
public void processRequest( String request )
{
System.out.println("Process the Request by Target Class: " + request);
}
}

FilterChain.java

import java.util.ArrayList;
import java.util.List;

public class FilterChain
{
private List<Filter> filters = new ArrayList<Filter>();
private Target       target;

public void addFilter( Filter filter )
{
filters.add(filter);
}

public void execute( String request )
{
for( Filter filter : filters )
{
filter.processRequest(request);
}
target.processRequest(request);
}

public void setTarget( Target target )
{
this.target = target;
}
}

FilterManager.java

public class FilterManager
{
FilterChain filterChain;

public FilterManager( Target target )
{
filterChain = new FilterChain();
filterChain.setTarget(target);
}

public void setFilter( Filter filter )
{
filterChain.addFilter(filter);
}

public void filterRequest( String request )
{
filterChain.execute(request);
}
}

Client.java

public class Client
{
FilterManager filterManager;

public void setFilterManager( FilterManager filterManager )
{
this.filterManager = filterManager;
}

public void sendRequest( String request )
{
filterManager.filterRequest(request);
}

public static void main( String[] args )
{
FilterManager filterManager = new FilterManager(new Target());
filterManager.setFilter(new AuthenticationFilter());
filterManager.setFilter(new LoggingFilter());
Client client = new Client();
client.setFilterManager(filterManager);
client.sendRequest("HOME");

}

}

Output

Authenticating the request by AuthenticationFilter : HOME
Request Tracking is done by LoggingFilter : HOME


Intercepting Filter Design Pattern - Class and Sequence Diagram

🚀 Master Object-Oriented Architecture!

Subscribe to Ram N Java for clean diagrams, enterprise design patterns, and clear step-by-step guides!

🔔 Subscribe to Ram N Java

Understanding the Architecture

The Intercepting Filter Design Pattern is an architectural pattern tailored for web and enterprise applications. It intercepts incoming client requests and outgoing responses to execute critical pre-processing and post-processing tasks—such as authentication, session verification, logging, and data compression—without modifying the business logic inside the target handler.

Class Diagram: Participants and Roles

To design this pattern properly, let us examine the main classes and interfaces that form the backbone of the architecture:

  • Filter (Interface): Declares the abstract execution method (e.g., execute(String request)) that all concrete filters implement.
  • Concrete Filters: Specific implementations that handle individual cross-cutting concerns (e.g., AuthenticationFilter, DebugFilter, AuditFilter).
  • FilterChain: Holds an ordered sequence of filters, executes them one after another, and forwards the processed request to the final target.
  • Target: The ultimate business destination, controller, servlet, or resource requested by the client.
  • FilterManager: Coordinates the creation and lifecycle of the FilterChain, attaches the required filters, and initiates request processing.
  • Client: The requester that invokes the FilterManager to access the protected target resource.

Sequence Diagram: Execution Flow Step-by-Step

The sequence diagram illustrates how messages move dynamically between objects at runtime:

  1. Client Triggers Request: The client sends a request to the FilterManager.
  2. Manager Assembles Chain: The FilterManager creates or configures the FilterChain and binds the designated Target.
  3. Sequential Filter Execution: The FilterChain calls each registered filter sequentially to run pre-processing tasks (such as inspecting headers or validating credentials).
  4. Delegation to Target: Once all filters finish their tasks without errors, the chain delegates execution to the Target object.
  5. Response Lifecycle: The target generates the response, which can optionally pass through the chain in reverse order for post-processing before reaching the client.

Key Design Benefits

  • Centralized Request Processing: Keeps common security, auditing, and transformation logic out of core business classes.
  • Loose Coupling: Filters are completely independent of one another and independent of the target resource.
  • Pluggable Components: You can add, reorder, or disable individual filters without refactoring or breaking existing business services.

Recommended Next Videos

Broaden your understanding of enterprise and structural patterns with these tutorials from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=5MppAW_lGnQ

Click the below Image to Enlarge
Intercepting Filter Design Pattern - Class and Sequence Diagram

Intercepting Filter Design Pattern - Introduction

🚀 Master Java Enterprise Architecture!

Subscribe to Ram N Java for beginner-friendly design pattern tutorials, clean code architectures, and step-by-step guides!

🔔 Subscribe to Ram N Java

Introduction to Intercepting Filter Pattern

In modern web and enterprise applications, incoming requests often require specialized handling before reaching their primary destination. The Intercepting Filter Design Pattern is an architectural pattern designed to intercept incoming requests and outgoing responses, applying critical pre-processing and post-processing tasks seamlessly.

Why Do We Need This Pattern?

When multiple services or servlets need similar administrative tasks—such as verifying security credentials, tracking user activity, or compressing payloads—hardcoding those operations into each individual handler creates heavy code duplication. The Intercepting Filter pattern solves this by:

  • Isolating Cross-Cutting Concerns: Separating logging, authentication, and encryption from business controllers.
  • Enabling Modularity: Each filter focuses exclusively on one specific operational task.
  • Declarative Chaining: Multiple filters can be combined in any designated order without altering client or target code.

How Interception Works

Rather than connecting directly to the destination resource, client requests flow through an interception pipeline:

  1. Pre-Processing: Filters inspect headers, authenticate tokens, decrypt incoming payloads, or audit access times.
  2. Target Delegation: If all filters pass successfully, the request reaches the target resource (such as a core servlet or controller).
  3. Post-Processing: The outgoing response can pass back through the filters to perform formatting, caching, or compression before returning to the client.

Core Architecture Participants

  • Filter: The pluggable component performing a dedicated check or transformation.
  • Filter Chain: The manager that coordinates sequential execution across registered filters.
  • Filter Manager: Creates and configures filter chains based on the incoming request route.
  • Target: The ultimate business resource handling the client request.

Recommended Next Videos

Continue mastering enterprise patterns with these related tutorials from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=XuIa6NsQAuA

Click the below Image to Enlarge
Intercepting Filter Design Pattern - Introduction

Monday, 12 August 2013

J2EE patterns - Presentation Tier

🚀 Master Enterprise Java & J2EE Architecture!

Subscribe to Ram N Java for clean, visual, and beginner-friendly programming tutorials!

🔔 Subscribe Now

Overview of J2EE Presentation Tier Patterns

In multi-tier enterprise Java (J2EE) applications, system components are categorized into three core architectural tiers:

  1. Presentation Tier: Manages client requests, processes HTTP input, coordinates navigation, and renders user interface views.
  2. Business Tier: Contains the enterprise logic, validation rules, and transactional processing.
  3. Integration Tier: Connects business logic to external databases, messaging services, and legacy backends.

Core Presentation Tier Design Patterns Checklist

The Presentation Tier addresses the challenges of web application structure, request preprocessing, view composition, and decoupling presentation logic from business systems:

  • 1. Intercepting Filter Pattern: Intercepts and manipulates incoming requests and outgoing responses declaratively for common services like logging, authentication, and encoding.
  • 2. Front Controller Pattern: Provides a centralized entry point to route, dispatch, and handle all incoming web requests (the cornerstone of frameworks like Spring MVC and Struts).
  • 3. Context Object Pattern: Encapsulates protocol-specific request and session information into a protocol-agnostic context object across layers.
  • 4. Application Controller Pattern: Centralizes and modularizes action routing and screen navigation flow away from the main controller.
  • 5. View Helper Pattern: Delegates view formatting, data transformation, and helper routines away from view templates (like JSPs) to dedicated helper classes.
  • 6. Composite View Pattern: Composes complex UI pages out of reusable, modular sub-views and tile templates.
  • 7. Dispatcher View Pattern: Coordinates view dispatching and response generation concurrently while managing screen flows.
  • 8. Service to Worker Pattern: Combines a dispatcher with large-scale request handling to delegate actions to worker components before rendering views.

Key Architectural Benefits

  • Centralized Request Processing: Consolidates security checks, session validation, and logging in one place.
  • Cleaner UI Separation: Prevents business or formatting clutter inside presentation templates.
  • Reusable View Components: Enables modular building blocks for web applications, drastically improving maintainability.

Recommended Enterprise & Architecture Tutorials:


Click here to watch in Youtube : https://www.youtube.com/watch?v=XeWCeX65RB0

Click the below Image to Enlarge
J2EE patterns - Presentation Tier

Tutorials