Filter vs Interceptor in Spring

·

3 min read

Hey Guys, In this blog we gonna cover about the what is filter and interceptor and what are the differences between . Without doing further delay, let get started .

What is Filter?

Filter is a web level concept. It’s main work is to modify or process all the incomming request or outgoing request from server. It works on serverlet level i.e each request hitting the server has to pass throught these filters . So, they are basically used for more general request-response tasks .

Usecase:

  1. Checking Headers or Body (for jwt authentication etc).

  2. Logging the request

  3. Add security rules like CORS policy

What is filter lifecycle:

Filter are intailised when the server start and are applied all the incomming reqeust.

How to implement filter:

Filter can be implement by

  1. Creating a class with @component annotation (Specifing the class is spring managed component)

  2. Implement the javax.serverlet.Filter

  3. Override the doFilter method

import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import java.io.IOException;

@Component
public class MyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
 FilterChain chain)
            throws IOException, ServletException {
        System.out.println("Filter applied before request reaches Controller");
        chain.doFilter(request, response);
        System.out.println("Filter applied after response from Controller");
    }
}

What is Interceptor?

Interceptor is a feature of Spring MVC . It controls the lifecycle of request and response. It works near the controller (i.e works before and after the controller logic).

Usecase:

  1. Checking Authorization for some endpoints

  2. Do some processing on request data

  3. Data validation

  4. Adding metadeta (for example: Adding headers)

What is interceptor lifecycle:

Interceptor get triggered when a request enter the controller.

How to implement interceptor:

The interceptor can be implemented by

  1. Create a class with @component notation

  2. Implement HandlerInterceptor

  3. It has three methods override them

    1. preHandle(): before controller logic

    2. postHandle(): after controller logic but before the response send to the client

    3. afterCompletion(): after the response is completly ready

       import org.springframework.stereotype.Component;
       import org.springframework.web.servlet.HandlerInterceptor;
       import javax.servlet.http.HttpServletRequest;
       import javax.servlet.http.HttpServletResponse;
      
       @Component
       public class MyInterceptor implements HandlerInterceptor {
      
           @Override
           public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
               System.out.println("Interceptor: Controller ke pehle");
               return true; // Request ko aage pass karne ke liye true return karna zaruri hai
           }
      
           @Override
           public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
               System.out.println("Interceptor: Controller ke baad par Response ke pehle");
           }
      
           @Override
           public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
               System.out.println("Interceptor: Response completely ready");
           }
       }
      
  4. Register the interceptor in WebMvcConfigurer class

     import org.springframework.beans.factory.annotation.Autowired;
     import org.springframework.context.annotation.Configuration;
     import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
     import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
     @Configuration
     public class MyInterceptorConfig implements WebMvcConfigurer {
    
         @Autowired
         private MyInterceptor myInterceptor;
    
         @Override
         public void addInterceptors(InterceptorRegistry registry) {
             registry.addInterceptor(myInterceptor);
         }
     }
    

Quick recap:

  1. Filter: General purpose, to modify request/response, works before controller.

  2. Interceptor: To handle controller specific logic

  3. Filter works on Servlet level , Interceptor works Spring level.

I hope you have understood what filter and interceptor is and what they do.

Happy Coding .

See you in another late night blog 😁