Spring HandlerInterceptor与Servlet过滤器 [英] Spring HandlerInterceptor vs Servlet Filters

查看:120
本文介绍了Spring HandlerInterceptor与Servlet过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HandlerInterceptor 可以现在配置为仅使用<mvc:interceptors>在某些URL上调用.

HandlerInterceptors in Spring can now be configured to be invoked only on certain URLs using <mvc:interceptors>.

Servlet过滤器可以实现相同的功能(日志记录,安全性等).那么应该使用哪一个呢?

Servlet Filters can achieve same functionality (logging, security etc). So which one should be used?

我认为使用Interceptors,可以使用ModelAndView对象与模型一起使用,因此它具有更多的优势.任何人都可以提出过滤器或拦截器比其他方法更具优势的方案吗?

I think with Interceptors, one can use ModelAndView object to work with Models so it has more advantages. Can anyone draw out scenarios where Filters or Interceptors have advantages over the other?

推荐答案

org.springframework.web.servlet.HanderInterceptor接口

The org.springframework.web.servlet.HanderInterceptor Interface JavaDoc itself has a two paragraphs that discuss this question:

HandlerInterceptor基本上类似于Servlet 2.3过滤器,但是 与后者相反,它仅允许使用 禁止执行处理程序本身的选项,以及 自定义后处理.过滤器功能更强大,例如它们 允许交换处理的请求和响应对象 下链.请注意,在web.xml中配置了过滤器, 在应用程序上下文中使用HandlerInterceptor.

HandlerInterceptor is basically similar to a Servlet 2.3 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实现的候选对象,尤其是 分解出通用处理程序代码和授权检查.在 另一方面,筛选器非常适合请求内容和视图 内容处理,例如多部分表单和GZIP压缩.这 通常显示何时需要将过滤器映射到某些内容 类型(例如图片)或所有请求.

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.

这篇关于Spring HandlerInterceptor与Servlet过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆