Filter vs. Interceptor in Spring Boot

Filter vs. Interceptor in Spring Boot

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.

  • init(FilterConfig config)?— This is invoked only once. It is used to initialize the filter.
  • doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain)?— This method is invoked every time a user send a request to any resource, to which the filter is mapped. It is used to perform filtering tasks.
  • destroy()?— This is invoked only once when filter is taken out of the service.

No alt text provided for this image

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.


  • preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)?— This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client.
  • postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
  • ModelAndView modelAndView)?— This is used to perform operations before sending the response to the client.
  • afterCompletion(HttpServletRequest request, HttpServletResponse response,
  • Object handler, Exception exception)?— This is used to perform operations after completing the request and response.

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.

No alt text provided for this image

Filters vs HandlerInterceptors

  • Filter?is related to the Servlet API and?HandlerIntercepter?is a Spring specific concept.
  • Interceptors will only execute after?Filters.
  • Fine-grained pre-processing tasks are suitable for?HandlerInterceptors (authorization checks, etc.)
  • Content handling related or generic flows are well-suited for?Filters (such as multipart forms, zip compression, image handling, logging requests, authentication etc.)
  • Interceptor’s?postHandle?method will allow you to add more model objects to the view but you can not change the HttpServletResponse since it's already committed.
  • Filter’s?doFilter?method is much more versatile than?Interceptor’s?postHandle. You can change the request or response and pass it to the chain or even block the request processing.
  • A?HandlerInterceptor?gives more fine-grained control than a filter because you have access to the actual target “handler”. You can even check if the handler method has a specific annotation.

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.

No alt text provided for this image






Nguyen Manh Ha

Fullstack Software Engineer, AWS Cloud Practitioner

1 年

great tutorial

回复

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

回复
Ashutosh Pathak

Tech Lead | Lead Guitarist

2 年

Nice one.

回复
Diego Nú?ez Silva

Senior Software Engineer Consultant (Java)

2 年

Very informative! Thanks for taking the time to create it.

回复
Syed Abdullah

Software Engineer @ Contour Software | .Net core | Microservices | REST APIs | Entity Framework | Sql Server | Flutter

2 年

Thanks a lot

回复

要查看或添加评论,请登录

Omar Ismail的更多文章

  • OAuth Grant Types (Authorization Code Grant)

    OAuth Grant Types (Authorization Code Grant)

    The authorization code grant type is used to obtain both access tokens and refresh tokens. The grant type uses the…

  • What is Apache Kafka?

    What is Apache Kafka?

    Reference : https://www.qlik.

    2 条评论
  • Multi-Tenant Architecture in a Nutshell

    Multi-Tenant Architecture in a Nutshell

    Thanks to the original writer and article :…

  • Microservices Communication!

    Microservices Communication!

    Thanks To: https://medium.com/design-microservices-architecture-with-patterns/microservices-communications-f319f8d76b71…

    2 条评论
  • What Are the New Features of SpringBoot3 ?

    What Are the New Features of SpringBoot3 ?

    Thanks to : https://medium.com/javarevisited/what-are-the-new-features-of-springboot3-6ddba9af664 1.

    1 条评论
  • OAuth 2.0!

    OAuth 2.0!

    Thanks to the original writer : https://medium.com/@isharaaruna OAuth2.

    2 条评论
  • How to Draw a Technical Architecture Diagram

    How to Draw a Technical Architecture Diagram

    Thanks to the original writer and article : https://levelup.gitconnected.

    2 条评论
  • Event Sourcing Versus Event-Driven Architecture

    Event Sourcing Versus Event-Driven Architecture

    Thanks to the original writer and article :…

  • Best Practices For Your API Versioning Strategy

    Best Practices For Your API Versioning Strategy

    API versioning is critical. But do you know all of the API versioning best practices? Is your API versioning strategy…

    1 条评论
  • Enterprise Architecture Tools

    Enterprise Architecture Tools

    Thanks to the original writer and article : https://medium.com/geekculture/enterprise-architecture-tools-b8165c8c9d7…

社区洞察

其他会员也浏览了