Struts2 Interceptors addresses the common concerns across different actions.
For example logging before and after an action is executed, security and much more.
Once the matching action is identified by the framework, it routes the
request through a list of configured Interceptors against the action known as Action Pre Processing.
Finally the action gets executed and the Interceptors are executed in the reverse
order known as Action Post Processing. Most of the Struts2 functionality lies in Interceptors.
Some of them are listed below,
ServletConfig interceptor - Its useful to set various Servlet specific object references on actions.
It set the appropriate object reference by verifying the framework specific interfaces
(SessionAware, RequestAware, ParameterAware, ServletRequestAware, ServletResponseAware and the ServletContextAware interface etc.)
implemented by action.
Exception interceptor - Its useful to handle the case where an unhandled exception is
thrown from an action. It maps the exception class to named Struts2 results.
Params interceptor - It provides the core auto binding functionality. It goes through
request parameters and set them to matching properties on action instance.
Validation interceptor - Its useful to perform validation on actions.
This example shows configuring and implementing Interceptors in Struts2.
The necessary libraries are shown below,
We can create an Interceptor by following one of the two approaches,
Here String result is the named result returned by its immediate Interceptor or action itself.
Interceptor can change the request flow by ignoring the named result returned from previous Interceptors and actions.
Its configuration in struts.xml is shown below,
Here logger is the Interceptor referenced from Struts2 default package (extends="struts-default").
And simpleInterceptor & simpleInterceptor2 are custom Interceptors
defined for the demo.
We can group the list of applicable Interceptors as Interceptor Stack.
From action we refer this group using interceptor-ref tag in the xml.
Also we can configure Interceptor stack applicable to all action with in a given package
instead of each Action individually.