70

HandlerInterceptors in Spring can now be configured to be invoked only on certain URLs using <mvc:interceptors>.

Servlet Filters can achieve same functionality (logging, security etc). So which one should be used?

I think with Interceptors, one can use ModelAndView object to work with Models so it has more advantages. Can anyone draw out scenarios where Filters or Interceptors have advantages over the other?

reevesy
  • 3,452
  • 1
  • 26
  • 23
aces.
  • 3,902
  • 10
  • 38
  • 48
  • 2
    A Servlet Filter is used in the web layer only, you can't use it outside of a web context. Interceptors can be used anywhere. That's the main difference. http://www.javabench.in/2011/10/java-difference-between-filter-and.html – Raúl May 28 '14 at 18:56

4 Answers4

64

The org.springframework.web.servlet.HanderInterceptor Interface JavaDoc itself has a two paragraphs that discuss this question:

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, a 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, 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.

Ralph
  • 118,862
  • 56
  • 287
  • 383
  • 2
    So now I have 2 view points. Apparently the previous post suggests HandlerInterceptors are more powerful. I understand that HandlerInterceptors are part of Spring Framework and outside Spring I don't think they can be used. But in Spring-based projects don't they have advantage over Filters? – aces. Nov 04 '11 at 19:39
  • 4
    @aces: yes: the main advantage of springframework HanderInterceptor is - that they can intercept between Controller Handling and View Rendering, - and they are spring Beans so it is easy to access other spring bean. – Ralph Jul 20 '15 at 08:43
28

Spring Handler interceptors allow you to hook into more parts of the request lifecycle, and get access to more information in the process. They're often more intimately coupled to the request/response cycle than filters.

Filters are more suitable when treating your request/response as a black box system. They'll work regardless of how the servlet is implemented.

If you're using Spring MVC, there's little reason to write new logic as a servlet filter. Everything filters can do, interceptors can do more easily and more elegantly.

Remember also, servlet filters have been around for much longer than interceptors.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 1
    So, in Spring based projects, instead of having a filter for handling urls serving static content, we can use Spring Handlerinterceptors. I do subscribe with your view point regarding HandlerInterceptors being more powerful than Filters. But can you think of a scenario(spring based app) where filters should be used instead? – aces. Nov 04 '11 at 19:39
  • 9
    @aces: The only scenario I can think of off hand is if you had multiple DispatcherServlets in the same webapp, and you wanted to intercept requests across all of them. This is rarely going to be the case, though. – skaffman Nov 05 '11 at 09:48
  • 13
    Spring Handler interceptors cant do one thing - wrapping the request / response objects in custom types. As far as I can tell you still need a Filter for that. – Erin Drummond Nov 18 '14 at 03:49
  • 1
    @ErinDrummond is correct - frameworks that customize ServletRequest or ServletResponse method implementations use wrappers and require that a Filter be used. Spring `HandlerInterceptor`s cannot do this. – Les Hazlewood Feb 18 '15 at 22:09
  • 1
    @skaffman - I know I'm bringing up an old question, but in the case of wanting to calculate request time, in the request filter, I'd be missing on some time spent by the request in the framework. Is this significant enough for me to be bothered with a servlet filter or will the handler interceptor give me an accurate enough value? – kapad Jul 12 '15 at 22:37
6

Servlet 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.

This behaviour allow to implement common functionality reused in many different contexts.

enter image description here

As shown in the figure above, the filter runs in the web container so its definition will also be contained in the web.xml file.

The filter include three main methods:

  1. init: Executed to initialize filter using init-param element in filter definition.
  2. doFilter: Executed for all HTTP incoming request that satisfy "url-pattern".
  3. destroy: Release resources used by the filter.

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 sofisticated behaviour because can access to all Spring context.

enter image description here

The Spring interceptor are execute in SpringMVC context so they have be defined in rest-servlet.xml file:

The interceptor include three main methods:

  1. preHandle: Executed before the execution of the target resource.
  2. afterCompletion: Executed after the execution of the target resource (after rendering the view).
  3. postHandle: Intercept the execution of a handler.
Noman Akhtar
  • 690
  • 1
  • 12
  • 17
6

With a Spring interceptor, you have access to the Handler which may be useful. Also, with a Spring interceptor, you have access to execute logic before the view renders and after the view is rendered.

smp7d
  • 4,947
  • 2
  • 26
  • 48
  • 3
    Filters( In Servlet) can change the response when it is going towards client(browser) from Servlet. In the same way can we change response or manipulate response object when Spring Controller is sending back response to Client (browser) ? If answer is NO then what is an alternative method to do so ? I don't want to use Filters (In Servlet ). – AmitG Jan 02 '14 at 17:08