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

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

问题描述

HandlerInterceptor在Spring中可以现在被配置为仅在使用 的特定 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?

我认为使用拦截器,可以使用 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 接口 JavaDoc 本身就有两段讨论这个问题:

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

HandlerInterceptor 基本上类似于 Servlet 2.3 Filter,但是与后者相反,它只允许自定义预处理禁止执行处理程序本身的选项,以及自定义后处理.过滤器更强大,例如它们允许交换所传递的请求和响应对象下链.请注意,过滤器在 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天全站免登陆