Design Pattern

Intercepting Filter Design Pattern – Core J2EE Patterns

Intercepting filter Design Pattern is one of the Java EE patterns. It is capable of creating pluggable filters which are responsible for processing common services. These services are processed in such a manner that there no changes required by the core request processing code. These filters are set to seize the requests coming in and responses going out, which allow the system pre and post processing. These filters can be removed or added in an unnoticeable manner which does not need the existing code to be altered. The intercepting filter pattern implicates the processing transparently which is also reusable after and before the standard request executes by page and front controllers.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Patterns“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.

Intercepting filter Design Pattern

The intercepting filters are applied and defined on a particular request before it passes the request to the actual aimed application. These filters are capable of authorizing, authenticating, tracking or logging the request. It then passes these request to their corresponding handlers. The structure of intercept design pattern is such that it has a filter, filter chain, filter manager, target, and client. Each of these handles their own part of the system.

Filter

The filter is responsible for performing a particular task before or after the execution of the request by its request handler.

Target

The target is, in fact, the target object- a request handler.

Filter chain

Filter chain carries a chain of filters which are to be implemented on the target, in different and defined order.

Filter manager

Filter manager is responsible for managing the filters and filter chain.

Client

The client is the object which sends the requests to the Target object.

Implementation and Use cases of Intercepting Filter Pattern

When an intercepting filter is sent a particular task to perform, it, after receiving the request, perform certain tasks on it. It passes the data to another filter object so that it filters it. That object, then, sends the filtered data back to the filter and the normal execution is continued. After, all this process, a requested output is produced.

Use Cases

These filters are required when the user need to perform logging or authentication. It enhances the security of the system. There are certain conditions, in which the user might need to implement the intercepting filter pattern. These conditions include; when an additional function is required to be added to the current web application when the main process is needed to be decorated, when the user needs to debug or when the preprocessing and post-processing is required for a particular client. It uncompresses the incoming request. The filter can be added or removed transparently and it can be triggered automatically. It gives the benefit of improved re-usability. It composes the deployment time. The intercepting filter pattern centralizes the control of the system. In the filter chain, every filter is coupled loosely and are, therefore, not efficient for sharing the information. The pattern offers improved flexibility within the system- the users are able to add or remove the common components flexibly and declaratively. The unnecessarily long filter chains with a large number of interceptors or filters can cause the performance efficiency to be reduced.

Implementation Filter strategies

The process is the intercepting filter pattern is such that, the client invokes a request and sends it to the filter manager. The filter manager is the creator of both, the filter chain and the filter object and it manages both as well. There is an exchange of processed and the processed data between filter object and filter chain. Filter chain then invokes the processed request back to the target (request handler).

There are certain strategies for implementing an intercepting filter. Some of them are; standard filter strategy, base filter strategy, template filter strategy, web services and message handling strategies and custom filter strategies.

Sample Implementation

We are going to create a FilterChain, FilterManager, Target, Client as various objects representing our entities. AuthenticationFilter and DebugFilter represent concrete filters.

Step 1 : Create Filter interface.
Filter.java

public interface Filter {
   public void execute(ServletRequest request);
}

Step 2 : Create Filter’s implementation classes.
DebuggingFilter.java

public class DebuggingFilter implements Filter{
  public void execute(ServletRequest request)  {
    //Do some filter processing here, such as 
    // displaying request parameters
    System.out.println("request log: " + request);
  }

AuthenticationFilter.java

public class AuthenticationFilter implements Filter {
   public void execute(ServletRequest request){
    //Do some filter processing here, such as 
    // displaying request parameters
      System.out.println("Authenticating request: " + request);
   }
}

Step 3 : Create Target class.
Target.java

public class Target {
   public void execute(ServletRequest request){
      System.out.println("Executing request: " + request);
   }
}

Step 4: Create Filter Chain class
FilterChain.java

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

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

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

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

Step 5: Create Filter Manager class.
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(ServletRequest request){
      filterChain.execute(request);
   }
}

Step 6: Create client class
Client.java

public class Client {
   FilterManager filterManager;

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

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

Create 7: Create a demo class
InterceptingFilterDemo.java

public class InterceptingFilterDemo {
   public static void main(String[] args) {
      ServletRequest request = //request object.
      FilterManager filterManager = new FilterManager(new Target());
      filterManager.setFilter(new AuthenticationFilter());
      filterManager.setFilter(new DebugFilter());

      Client client = new Client();
      client.setFilterManager(filterManager);
      client.sendRequest(request);
   }
}
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago