So sánh filter servlet và interceptor năm 2024

A filter performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use.

The servlet container calls the init method exactly once after instantiating the filter. The init method must complete successfully before the filter is asked to do any filtering work.

Filter performs the filtering operation in the doFilter method, and it is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.

The destroy method is only called once all threads within the filter’s doFilter method have exited or after a timeout period has passed. This method gives the filter an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the filter’s current state in memory.

Some of the use cases where we can use filters are: 1. Authentication 2. Logging and Auditing 3. Image conversion 4. Data compression 5. Encryption

What is Handler Interceptor?

A HandlerInterceptor gets called before the appropriate HandlerAdapter triggers the execution of the handler itself. This mechanism can be used for a large field of preprocessing aspects, e.g. for authorization checks, or common handler behavior like locale or theme changes. Its main purpose is to allow for factoring out repetitive handler code.

HandlerInterceptor is very similar to Servlet Filter, but it just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing. Filters are more powerful, as they allow for exchanging the…

Looking to compare Spring Interceptors and Filters? This ultimate comparison guide will help you understand the pros and cons of each and how they impact the execution flow of your Spring Boot application.

Context

When building Spring Boot applications, it’s common to come across the terms “interceptor” and “filter”. Both are used for intercepting requests and responses in the application, but there are some key differences between the two. In this blog post, we’ll explore the difference between Spring Interceptors and Filters.

Spring Interceptors are used to intercept requests and responses at the controller level. They are executed before the controller method is invoked and after the controller method has returned. This means that you can modify the request or response before it reaches the controller or after it has been processed by the controller.

Interceptors are typically used for:

  • Authentication and authorization
  • Logging
  • Performance monitoring
  • Customizing the request or response

Spring Interceptors are implemented using the HandlerInterceptor interface. This interface defines three methods:

  • preHandle() – Executed before the controller method is invoked. This method returns a boolean value indicating whether to continue processing the request or abort the request.
  • postHandle() – Executed after the controller method has returned, but before the view is rendered. This method allows you to modify the model or view before rendering.
  • afterCompletion() – Executed after the view has been rendered. This method allows you to perform any cleanup tasks.

Filters

Filters, on the other hand, are used to intercept requests and responses at the servlet level. They are executed before the request reaches the servlet and after the response has been generated. Filters can be used to modify the request or response or to perform some other action on the request or response.

Filters are typically used for:

  • Authentication and authorization
  • Compression and decompression
  • Encryption and decryption
  • URL rewriting

Filters are implemented using the jakarta.servlet.Filter interface. This interface defines one method:

  • doFilter() – Executed for each request and response that passes through the filter. This method allows you to modify the request or response, or to perform some other action on the request or response.

Key Differences

The key difference between Spring Interceptors and Filters is the level at which they operate. Interceptors operate at the controller level, while Filters operate at the servlet level. This means that Interceptors have access to the controller and can modify the model and view, while Filters do not have access to the controller and can only modify the request and response.

Another difference is the order in which they are executed. Interceptors are executed before and after the controller method, while Filters are executed before and after the servlet. This means that Interceptors have more fine-grained control over the request and response, while Filters have more general control over the request and response.

Sr. No.AspectSpring InterceptorsFilters1.Level of operationController levelServlet level2.AccessAccess to controllerNo access to controller3.Execution orderBefore/after controller methodBefore/after servlet4.Defined inSpring FrameworkServlet specification5.InterfaceHandlerInterceptorjakarta.servlet.FilterSpring Interceptors vs Filters

Request Execution Flow

  1. A request is received by the Spring Boot application.
  2. The request passes through the filter chain, which is responsible for handling low-level tasks such as authentication and URL rewriting. Each filter in the chain can modify the request or response before passing it on to the next filter.
  3. Once the request has passed through the filter chain, it reaches the DispatcherServlet.
  4. The DispatcherServlet matches the request to the appropriate controller method.
  5. Before the controller method is invoked, the request passes through the interceptor chain, which is responsible for handling high-level tasks such as logging and performance monitoring. Each interceptor in the chain can modify the request or response before passing it on to the next interceptor.
  6. Once the request has passed through the interceptor chain, the controller method is invoked.
  7. The controller method generates a response, which passes back through the interceptor chain.
  8. After the response has passed through the interceptor chain, it passes back through the filter chain. Each filter in the chain can modify the response before it is sent back to the client.

Conclusion

In summary, Spring Interceptors and Filters are both used for intercepting requests and responses in web applications. Interceptors operate at the controller level, while Filters operate at the servlet level. Interceptors have more fine-grained control over the request and response, while Filters have more general control over the request and response. Both Interceptors and Filters are useful tools for customizing and enhancing web applications, and it’s important to understand the differences between them when choosing which to use in your application.