Filter vs Interceptor in Spring
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:
Checking Headers or Body (for jwt authentication etc).
Logging the request
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
Creating a class with @component annotation (Specifing the class is spring managed component)
Implement the javax.serverlet.Filter
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:
Checking Authorization for some endpoints
Do some processing on request data
Data validation
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
Create a class with @component notation
Implement HandlerInterceptor
It has three methods override them
preHandle(): before controller logic
postHandle(): after controller logic but before the response send to the client
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"); } }
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:
Filter: General purpose, to modify request/response, works before controller.
Interceptor: To handle controller specific logic
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 😁