Difference between Interceptor and Filter in Spring MVC

后端 未结 3 793
盖世英雄少女心
盖世英雄少女心 2020-12-04 04:57

I\'m a little bit confused about Filter and Interceptor purposes.

As I understood from docs, Interceptor is run between reque

3条回答
  •  萌比男神i
    2020-12-04 05:31

    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

提交回复
热议问题