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?
Filter is related to the Servlet API and HandlerIntercepter is a Spring specific concept. Interceptors will only execute after Filters.
Interceptor is an object that is invoked at the preprocessing and postprocessing of a request. In Struts 2, interceptor is used to perform operations such as validation, exception handling, internationalization, displaying intermediate result etc.
In the web. xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes the Struts framework and handles all requests. This filter can contain initialization parameters that affect what, if any, additional configuration files are loaded and how the framework should behave.
FilterDispatcher was the filter that was provided by Struts 2 for handling all request which needs to be controlled by struts framework. After Struts 2.1. 3 use of this filter was deprecated.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With