La verdad no entiendo cual es el propósito de cada uno ya que realizan tareas muy similares.
¿Alguien me podría explicar cual es la diferencia entre un Interceptor y un Filter en Spring?
Stack Overflow en español es un sitio de preguntas y respuestas para programadores y profesionales de la informática. Solo te toma un minuto registrarte.
Regístrate para unirte a esta comunidadDe la propia documentación de Spring se puede extraer la siguiente explicación:
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.
Lo que viene a decir es que los filtros son más idóneos para manejo de requests y contenido relacionado con las vistas, mientras que los interceptores son más adecuados para tareas de pre-procesado, como pueden ser comprobaciones de autenticación.
Una ventaja que tienen los interceptores con respecto a los filtros, es que son capaces de interceptar entre el controlador y el renderizado de la vista. Por otra parte los interceptores son Beans
de Spring, por lo que tienes acceso a todo el contexto desde ellos.
javax.servlet.Filter
?