java spring filter_java – Spring MVC中Interceptor和Filter之间的区别

来自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压缩.这通常显示何时需要将过滤器映射到某些内容类型(例如图像)或所有请求.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值