HandlerInterceptor
基本上类似于Servlet Filter
,但是在
与后者相反,它仅允许使用
禁止执行处理程序本身的选项和自定义
后期处理.过滤器功能更强大,例如,它们允许
交换流传下来的请求和响应对象
链.请注意,在web.xml
中配置了一个过滤器,
HandlerInterceptor
在应用程序上下文中.
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.
作为基本准则,与处理程序相关的细粒度预处理任务
是HandlerInterceptor
实现的候选对象,尤其是
分解出通用处理程序代码和授权检查.在
另一方面,Filter
非常适合请求内容和视图
内容处理,例如多部分表单和GZIP压缩.这
通常显示何时需要将过滤器映射到某些内容
类型(例如图片)或所有请求.
As a basic guideline, fine-grained handler-related pre-processing 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.
话虽这么说
那么Interceptor#postHandle()
和
Filter#doFilter()
?
postHandle
将在处理程序方法调用之后但呈现视图之前被调用.因此,您可以向视图中添加更多模型对象,但是不能更改HttpServletResponse
,因为它已经提交.
postHandle
will be called after handler method invocation but before the view being rendered. So, you can add more model objects to the view but you can not change the HttpServletResponse
since it's already committed.
doFilter
比postHandle
具有更多的用途.您可以更改请求或响应并将其传递到链上,甚至阻止请求处理.
doFilter
is much more versatile than the postHandle
. You can change the request or response and pass it to the chain or even block the request processing.
此外,在preHandle
和postHandle
方法中,您可以访问处理请求的HandlerMethod
.因此,您可以基于处理程序本身添加预处理/后处理逻辑.例如,您可以为具有某些注释的处理程序方法添加逻辑.
Also, in preHandle
and postHandle
methods, you have access to the HandlerMethod
that processed the request. So, you can add pre/post-processing logic based on the handler itself. For example, you can add a logic for handler methods that have some annotations.
在哪些用例中应该使用的最佳实践是什么?
What is the best practise in which use cases it should be used?
正如文档所说,与处理程序相关的细粒度预处理任务是HandlerInterceptor
实现的候选对象,尤其是分解出的公共处理程序代码和授权检查.另一方面,Filter
非常适合请求内容和视图内容处理,例如多部分表单和GZIP压缩.这通常显示何时需要将过滤器映射到某些内容类型(例如图像)或所有请求.
As the doc said, fine-grained handler-related pre-processing 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.
这篇关于Spring MVC中的拦截器和过滤器之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!