Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Execution Order: Filter and Interceptor

I'm developing a spring MVC application that uses a filter implementing javax.servlet.Filter and an Interceptor extending org.springframework.web.servlet.handler.HandlerInterceptorAdapter.

As far as I know, the control flow of Spring MVC is something like this:

  1. Request arrives at DispatcherServlet.
  2. DispatcherServlet sends it to Interceptor and the overrided preHandle method is executed.
  3. Request arrives at the matching Controller.
  4. After processing the request, if postHandle method of interceptor is also overrided Spring executes its code.
  5. DispatcherServlet uses the view resolver and sends the model to view, rendering it.

Doing some tests I can see my filter is always executed BEFORE the preHandle method. It seems to be the first executed thing after DispatcherServlet. It's ok, but I do not find the reason for this behaviour. Someone with a good explanation?

Thanks!

UPDATE: Possibility: It's because filter is defined in web.xml (like DispatcherServlet) so Filter is executed before DispatcherServlet?

like image 346
Emilio Avatar asked Nov 13 '14 12:11

Emilio


People also ask

Which one is called first filter or interceptor?

Interceptors will only execute after Filters. Fine-grained pre-processing tasks are suitable for HandlerInterceptors (authorization checks, etc.)

What is difference between filter and interceptor in Spring?

Filters can modify inbound and outbound requests and responses including modification of headers, entity and other request/response parameters. Interceptors are used primarily for modification of entity input and output streams. You can use interceptors for example to zip and unzip output and input entity streams.

What is the difference between postHandle () and afterCompletion ()?

postHandle() : After a request is handled by a request handler. It gives access to the returned ModelAndView object, so you can manipulate the model attributes in it. afterCompletion() : After the completion of all request processing i.e. after the view has been rendered.


1 Answers

It's perfectly fine as Filter's are part of Servlet specification.

Filters are called by your Server(tomcat). while Interceptors are called by Spring.

like image 160
Santosh Joshi Avatar answered Sep 20 '22 12:09

Santosh Joshi