Difference between Filter and Interceptor in Spring

1

I really do not understand what is the purpose of each one since they perform very similar tasks.

Could someone explain to me what is the difference between an Interceptor and a Filter in Spring?

    
asked by Gemasoft 31.03.2017 в 00:34
source

1 answer

2

From the documentation from Spring you can extract the following explanation:

  

HandlerInterceptor is basically similar to a Servlet 2.3 Filter, but in contrast to the latter 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, for example, they allow for exchanging the request and response objects that are handed down the chain. Note that a filter gets configured in web.xml, to HandlerInterceptor in the application context.

     

As a basic guideline, fine-grained handler-related preprocessing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, to Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.

What it comes to saying is that filters are more suitable for handling requests and content related to views, while interceptors are more suitable for pre-processing tasks, such as authentication checks.

An advantage that the interceptors have with respect to the filters is that they are capable of intercepting between the controller and the rendering of the view. On the other hand the interceptors are Beans of Spring, so you have access to the entire context from them.

    
answered by 28.04.2017 в 11:38