Pages Navigation Menu

Coding is much easier than you think

Interceptors in Struts 2

 

  • Interceptors are introduced as part of the Struts2 framework, power mechanism for controlling request and are responsible for the most of request processing.

 
Request Processing Life Cycle Workflow in Struts 2

  • Interceptors are invoked by controller before and after invoking action and sits between the controller and action.
  • An interceptor allows common, cross-cutting tasks to be defined into a clean, reusable component, which is different than the “action” code.
  • Tasks like data validation, type conversion, and file upload are done using interceptors in Struts2.0.
  • The built-in interceptors, declared in the “defaultStack” of the “struts-default package”, handle most of the fundamental tasks.

 

Functioning of Interceptors

  • From architectural point of view, interceptors improve separation of concerns in web applications.
  • An example of a pre-processing task is the data transfer achieved with the “params” interceptor.
  • Instead of having a simple controller that directly invokes an action, we now have a component that sits between the “controller” and the “action”.
  • In Struts 2, no action is invoked in isolation, the invocation of an action is a layered process. It always includes the execution of a stack of interceptors prior to and after the actual execution of the action itself.
  • Rather than directly invoking the action’s execute ( ) method, the framework creates an object called an “ActionInvocation”. This object encapsulates the action. Subsequently, all the interceptors that have been configured to fire before and after that “action” start their execution.

 

Interceptor Order

Diagrammatic Representation

actioninvocation

  • The figure above represents the normal workflow; here none of the interceptors have diverted the invocation. This “action” will ultimately execute and return a “control string” that selects the appropriate “result”.
  • After the “result” execution, each of the interceptors, in reverse order, gets a chance to do some post-processing work.
  • As we will see, the interceptors have access to the “action” and other contextual values. This allows them to be aware of what is happening during the processing.
  • One of the powerful functional aspects of “interceptors” is their “ability to alter the workflow of the invocation”.
  • As we noted, the figure shown in the above depicts an instance where none of the interceptors has intervened in the workflow. It thus allows the “action” to execute, and determine the result that should render the view.
  • Sometimes, one of the interceptors will determine that the “action should not execute”. In such cases, the interceptor can halt the workflow by itself by returning a “control string”.

 
In our next article we shall learn to implement a custom interceptor in struts 2