Saturday, January 9, 2010

Struts 2 interceptors overview


Interceptors are are one of the most powerful features in struts 2. Interceptors are useful because they enable you to perform common tasks across actions withoug having the need to recompile the code. Interceptors are configured in the struts onfiguration file for an action.

Interceptors are executed in the sequence in which they are declared. A set of interceptors that are required to execute in a sequence can be grouped together to form an interceptor stack.

Interceptors are declared in the struts.xml file inside a package.
Following is an example of interceptor declaration in struts.xml





 
 


As already mentioned Interceptors are executed in a sequence. They can be grouped together and the grouping is given a name. For example :




 
 
 
 
  
  
 


The 'name' attribute of interceptor-ref element can take an interceptor name or an interceptor stack name as its value. For example,




 
 
 
 
 
  
  
 
 
 
  
  
 


So, now we are done with interceptor declaration. So, how do we use these interceptors for our action classes? Following is an example of using the above interceptors for an action class.




 .
 .
 interceptor declarations
 .
 .
 
 
  
  /success.jsp
 



In the above example, we have cofigured the 'iName1' interceptor to execute before the methods of the action class get executed. You can also configure an interceptor stack to execute for an action. Example :




 .
 .
 interceptor declarations
 .
 .
 
 
  
  
  /success.jsp
 


When a package extends another package, it inherits all the configuration of the parent package including interceptors and interceptor stacks. So by extending the struts-default package, we get access to several useful preconfigured interceptor stacks namely




  • defaultStack
  • completeStack
  • basicStack

and many other interceptor stacks, and also a number of interceptors namely



  • exception
  • servlet-config
  • prepare
  • static-params
  • params
  • conversion-error
  • validation
  • workflow
  • model-driven
  • chain
  • i18n
  • execAndWait


Sometimes you need to execute a given interceptor/interceptor stack for all the actions in a package, and it can become quite frustrating to configure the same interceptor for each action. This can be avoided by configuring the package to have a default interceptor for all its actions. For example, in our code sample, if we want the 'myInterceptorStack' interceptor stack to be the default interceptor stack of that package, then we need to simply add one more element to the package element. Example :




 .
 .
 interceptor declarations
 .
 .
 
 .
 .
 action declarations
 .
 .
 
 


Well, thats it. :>



Signing Off
Ryan

No comments: