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?
What is the best practise in which use cases it should be used?
In this picture where works Filter
s and Interceptor
s?
This question is related to
java
spring
spring-mvc
spring-boot
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 handlerInterceptor 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 handlerMapping, and there may be multiple handlerMappings.
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.
Reference: http://static.springframework.org/sp...ng-interceptor
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 them 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 acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.
Source: Stackoverflow.com