过滤器与拦截器在Struts 2中 [英] Filters vs Interceptors in Struts 2
问题描述
在我阅读Struts 2的书中,似乎拦截器被推送,甚至跟着一个教程编写一个身份验证拦截器,以确保用户登录。但是,如果用户试图访问一个没有关联的动作的URL,拦截器不会捕获它,这意味着我必须将一个动作与每个我想要保护的jsp关联起来。这看起来不对。
我可以创建一个验证过滤器来处理URL,这样我就不必这样做了,但是,那么拦截器
最重要的区别是拦截器是Struts 2框架的一部分,只是部分请求处理由Struts 2框架完成。另一方面,过滤器是Servlet规范的一部分;换句话说,它们是Servlet API的一部分。如果你使用的是Struts 2,你应该使用拦截器来围绕你的Struts 2动作来包装功能。如果您试图围绕来自您的Web应用程序的请求打包功能,但不能被Struts 2处理,那么过滤器可能更合适。
顺便说一下,整个Struts 2框架都部署在web应用程序中配置的过滤器中,在webapp的部署描述符(web.xml)中声明:
< filter>
< filter-name> struts2< / filter-name>
< filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter< / filter-class>
< / filter>
< filter-mapping>
< filter-name> struts2< / filter-name>
< url-pattern> / *< / url-pattern>
< / filter-mapping>
此过滤器被配置为捕获所有请求的URL模式,是进入整个Struts 2框架。
我希望有帮助。
What's the difference, really, between filters and interceptors? I realize that interceptors fire before and after an action, recursively, and filters can be configured to fire on actions and on certain url patterns. But how do you know when to use each one?
In the book I'm reading on Struts 2, it seems that interceptors are being pushed and I even followed a tutorial to write an Authentication Interceptor to make sure a user is logged in. However, if the user tries to access a URL that doesn't have an action associated with it, the interceptor doesn't catch it, which means I'd have to associate an action with every jsp that I want to be secure. That doesn't seem right.
I can make an Authentication Filter that handles URLs so that I don't have to do that, but then, what's the point of interceptors?
The most significant difference is that "interceptors" are a part of the Struts 2 framework, and are only part of the request handling that is done by the Struts 2 framework. "Filters" on the other hand are a part of the Servlet Specifcation; in other words, they are part of the Servlet API. If you are using Struts 2, you should use interceptors for wrapping functionality around your Struts 2 actions. If you are trying to wrap functionality around requests coming to your webapp, but not being handled by Struts 2, then a filter might be more appropriate.
BTW, the entire Struts 2 Framework is deployed inside a filter configured in your web app, declared in your webapp's deployment descriptor ( web.xml ) like:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
This filter, which is configured to catch all requests URL patterns, is the entry point into the entire Struts 2 framework.
I hope that helps.
这篇关于过滤器与拦截器在Struts 2中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!