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?
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.
The
org.springframework.web.servlet.HanderInterceptor
Interface JavaDoc itself has a two paragraphs that discuss this question: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.