来自HandlerInterceptpter的
javadoc:
HandlerInterceptor is basically similar to a Servlet 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.
就这样说:
So where is the difference between PostHandle() in Interceptor and
doFilter() in Filter?
postHandle将在处理程序方法调用之后调用,但在呈现视图之前.因此,您可以向视图添加更多的模型对象,但是由于已经提交了HttpServletResponse,所以不能更改. doFilter比postHandle更加通用.您可以更改请求或响应,并将其传递给链,甚至阻止请求处理.
另外,在PreHandle和postHandle方法中,您可以访问处理请求的HandlerMethod.因此,您可以根据处理程序本身添加前置后处理逻辑.例如,您可以为具有一些注释的处理程序方法添加逻辑.
What is the best practise in which use cases it should be used?
正如文档所述,细粒度处理程序相关的预处理任务是HandlerInterceptor实现的候选者,特别是考虑了常规的处理程序代码和授权检查.另一方面,过滤器非常适合请求内容和查看内容处理,如多部分表单和GZIP压缩.这通常显示何时需要将过滤器映射到某些内容类型(例如图像)或所有请求.