Difference between Interceptor and Filter in Spring MVC
Asked Answered
C

4

188

I'm a little bit confused about Filter and Interceptor purposes.

As I understood from docs, Interceptor is run between requests. On the other hand Filter is run before rendering view, but after Controller rendered response.

So where is the difference between postHandle() in Interceptor and doFilter() in Filter?

Spring MVC sheme What is the best practise in which use cases it should be used? In this picture where works Filters and Interceptors?

Clump answered 7/3, 2016 at 23:51 Comment(0)
W
140

From HandlerIntercepter's javadoc:

HandlerInterceptor is basically similar to a Servlet 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, a HandlerInterceptor in the application context.

As a basic guideline, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a 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.

With that being said:

So where is the difference between Interceptor#postHandle() and Filter#doFilter()?

postHandle will be called after handler method invocation but before the view being rendered. So, you can add more model objects to the view but you can not change the HttpServletResponse since it's already committed.

doFilter is much more versatile than the postHandle. You can change the request or response and pass it to the chain or even block the request processing.

Also, in preHandle and postHandle methods, you have access to the HandlerMethod that processed the request. So, you can add pre/post-processing logic based on the handler itself. For example, you can add a logic for handler methods that have some annotations.

What is the best practise in which use cases it should be used?

As the doc said, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a 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.

Whew answered 7/3, 2016 at 23:55 Comment(5)
Note that a filter gets configured in web.xml, a HandlerInterceptor in the application context??? can u plz explain?Philoprogenitive
Filter is related to the Servlet API and HandlerIntercepter is a Spring specific concept. In order to register a servlet filter, you can either register it using the old web.xml (Servlet 2.5 and older versions) or the new programmatic approach (Servlet 3+). Since the HandlerIntercepter is just a Spring abstraction, you should register in the Spring's contextWhew
Filter is related to the Servlet API and HandlerIntercepter is a Spring specific concept. coorect! but whatever u r registering by web.xml is part of WebApplication which is single per dispatcher,so servlet and filter both ate associated with context,it is a good practice to associate interceptor and filter with rootContext so if u hv multiple dispatcher all can share same.Philoprogenitive
which one is better suite for requst(body, headers) logging?Hourglass
Which is better for Authentication, Authorisation, CORS, security ?Jens
K
78

From baeldung:

filters_vs_interceptors

Filters intercept requests before they reach the DispatcherServlet, making them ideal for coarse-grained tasks such as:

Authentication
Logging and auditing
Image and data compression
Any functionality we want to be decoupled from Spring MVC

HandlerIntercepors, on the other hand, intercepts requests between the DispatcherServlet and our Controllers. This is done within the Spring MVC framework, providing access to the Handler and ModelAndView objects. This reduces duplication and allows for more fine-grained functionality such as:

Handling cross-cutting concerns such as application logging
Detailed authorization checks
Manipulating the Spring context or model
Krieg answered 22/2, 2022 at 20:33 Comment(3)
The picture is very informative. Thank you.Coh
Good explanation and an example or Interceptor is the usage of AOP.Thales
The best answer hands down. Thanks!Kirsten
D
42

Filter: - A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each HTTP response. This way is possible to manage HTTP incoming requests before they reach the resource, such as a JSP page, a servlet or a simple static page; in the same way, is possible to manage HTTP outbound response after resource execution.

Interceptor: - Spring Interceptors are similar to Servlet Filters but they act in Spring Context so are powerful to manage HTTP Request and Response but they can implement more sophisticated behaviour because can access all Spring context.

Deferral answered 21/12, 2018 at 6:16 Comment(5)
source: mkjava.com/tutorial/filter-vs-interceptor have to mention sourceFiftyfifty
what about Spring security filter , it gives you spring context also.Languish
updated source: mkjava.com/tutorial/filter-vs-interceptor.htmlBoudicca
"as the name suggests"... it doesn't really suggest that though, does it?Flyspeck
@Languish Abosolutly yes. Spring Filter and intecerptor can acces all this context man because IOC conatiner stars before them.Thales
O
12

A HandlerInterceptor gives you more fine-grained control than a filter because you have access to the actual target "handler" - this means that whatever action you perform can vary depending on what the request is actually doing (whereas the servlet filter is generically applied to all requests - only able to take into account the parameters of each request). The handler interceptor also provides 3 different methods, so that you can apply behavior prior to calling a handler after the handler has completed but prior to view rendering (where you may even bypass view rendering altogether), or after the view itself has been rendered. Also, you can set up different interceptors for different groups of handlers - the interceptors are configured on the handler mapping, and there may be multiple handler mappings.

Therefore, if you have a need to do something completely generic (e.g. log all requests), then a filter is sufficient - but if the behavior depends on the target handler or you want to do something between the request handling and view rendering, then the HandlerInterceptor provides that flexibility.

Oakland answered 2/12, 2016 at 13:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.