Filter vs. Interceptor in Spring Boot
Omar Ismail
Senior Software Engineer @ Digitinary | Java 8 Certified? | Spring & Spring Boot?????? | AWS? | Microservices ?? | RESTFul Apis & Integrations ?? FinTech ?? | Open Banking ?? | Digital Payments and Transformation??
What is a Servlet?
It is a Java class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model.
Java Servlet technology defines HTTP-specific servlet classes. The?javax.servlet?and?javax.servlet.http?packages provide interfaces and classes for writing servlets.?Servlet?in “javax.servlet” package declares three essential methods for the life cycle of a servlet — init(), service(), and destroy().
What is a Servlet Container?
Servlets run in a?servlet container?which handles the networking side (e.g. parsing an HTTP request, connection handling etc).?Tomcat?is the most popular one.
Filter
It?is a Java class which is executed by the?servlet container?for each incoming HTTP?request?and for each HTTP?response.
Requests always first pass through Filter instances, before reaching a Servlet.
If you have multiple custom filters in your application, you can define the order with “@Order” annotation.
Interceptor
Spring Interceptors are similar to Servlet Filters. An interceptor just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing, having access to Spring Context.
HandlerInterceptor :?HandlerInterceptor instances are executed as part of the request handling inside the DispatcherServlet (which implements?javax.servlet.Servlet).
HandlerInterceptorAdapter:?If you would like to provide a custom implementation and only care for a few of their methods (if you do not want to create empty methods that requires overriding), it is better to implement an adapter.
Filters vs HandlerInterceptors
Spring Cloud Gateway Custom Filters
GlobalFilter
Global Filters affect every single request.
GatewayFilter
Gateway Filters applies to only some routes.
Order:?If we want to configure the position of the filter in the filter chain, we can retrieve an?OrderedGatewayFilter?instance.
Fullstack Software Engineer, AWS Cloud Practitioner
1 年great tutorial
Java/Golang Developer
1 年Hi nice blog, but Can you know me why Filters?used for authentication and HandlerInterceptors?used for authorization?check ? Can I write code authentication and authorization in one class Filter or HandlerInterceptors? ? Omar Ismail
Tech Lead | Lead Guitarist
2 年Nice one.
Senior Software Engineer Consultant (Java)
2 年Very informative! Thanks for taking the time to create it.
Software Engineer @ Contour Software | .Net core | Microservices | REST APIs | Entity Framework | Sql Server | Flutter
2 年Thanks a lot