Struts2 provides very powerful mechanism of controlling a request using Interceptors. Interceptors are responsible for most of the request processing. They are invoked by the controller before and after invoking action, thus they sits between the controller and action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc
Struts2 comes with default list of Interceptors already configured in the application in struts-default.xml file. We can create our own custom Interceptors and plugin into a Struts2 based web application.
Framework creates an object of ActionInvocation that encapsulates the action and all the interceptors configured for that action. Each interceptor’s are called before the action gets called. Once the action is called and result is generated, each interceptor’s are again called in reverse order to perform post processing work. Interceptors can alter the workflow of action. It may prevent the execution of action.
There are many interceptors provided by struts 2 framework. We have option to create our own interceptors. The struts 2 default interceptors are as follows:
1) alias It converts similar parameters that have different names between requests.
3) chain If it is used with chain result type, it makes the properties of previous action available in the current action.
4) checkbox It is used to handle the check boxes in the form. By this, we can detect the unchecked checkboxes.
5) cookie It adds a cookie to the current action.
6) conversionError It adds conversion errors to the action's field errors.
7) createSession It creates and HttpSession object if it doesn't exists.
8) clearSession It unbinds the HttpSession object.
9) debugging It provides support of debugging.
11) execAndWait It sends an intermediate waiting page for the result.
12) exception It maps exception to a result.
13) fileUpload It provides support to file upload in struts 2.
14) i18n It provides support to internationalization and localization.
15) jsonValidation It provides support to asynchronous validation.
16) logger It outputs the action name.
17) store It stores and retrieves action messages, action errors or field errors for action that implements ValidationAware interface.
18) modelDriven It makes other model object as the default object of valuestack.
19) scopedModelDriven It is similar to ModelDriven but works for action that implements ScopedModelDriven
20) params It populates the action properties with the request parameters.
22) prepare It performs preparation logic if action implements Preparable interface.
23) profiling It supports action profiling.
24) roles It supports role-based action.
25) scope It is used to store the action state in the session or application scope.
26) servletConfig It provides access to maps representing HttpServletRequest and HttpServletResponse.
28) staticParams It maps static properties to action properties.
29) timer It outputs the time needed to execute an action.
30) token It prevents duplication submission of request.
31) tokenSession It prevents duplication submission of request.
32) validation It provides support to input validation.
33) workflow It calls the validate method of action class if action class implements Validateable interface.
Using custom interceptors in your application is an elegant way to provide cross-cutting application features. Creating a custom interceptor is easy; the interface that needs to be extended is the followingInterceptor interface:
As the names suggest, the init() method provides a way to initialize the interceptor, and the destroy() method provides a facility for interceptor cleanup. Unlike actions, interceptors are reused across requests and need to be thread-safe, especially the intercept() method.
The ActionInvocation object provides access to the runtime environment. It allows access to the action itself and methods to invoke the action and determine whether the action has already been invoked.
If you have no need for initialization or cleanup code, the AbstractInterceptor class can be extended. This provides a default no-operation implementation of the init() and destroy() methods.
Create Interceptor Class:
Let us create following MyInterceptor.java in Java Resources > src folder:
As you notice, actual action will be executed using the interceptor by invocation.invoke() call. So you can do some pre-processing and some post-processing based on your requirement.
The framework itself starts the process by making the first call to the ActionInvocation object's invoke(). Each time invoke() is called, ActionInvocation consults its state and executes whichever interceptor comes next. When all of the configured interceptors have been invoked, the invoke() method will cause the action itself to be executed. Following digram shows the same concept through a request flow:
Create Action Class:
Let us create a java file HelloWorldAction.java under Java Resources > src with a package namecom.tutorialspoint.struts2 with the contents given below.
This is a same class which we have seen in previous examples. We have standard getters and setter methods for the "name" property and an execute method that returns the string "success".
Create a View
Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project.
Create main page:
We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where a user can click to tell the Struts 2 framework to call the a defined method of the HelloWorldAction class and render the HelloWorld.jsp view.
The hello action defined in the above view file will be mapped to the HelloWorldAction class and its execute method using struts.xml file.
Now we need to register our interceptor and then call it as we had called default interceptor in previous example. To register a newly defined interceptor, the ... tags are placed directly under the tag ins struts.xml file. You can skip this step for a default interceptors as we did in our previous example. But here let us register and use it as follows:
It should be noted that you can register more than one interceptors inside tag and same time you can call more than one interceptors inside the <action> tag. You can call same interceptor with the different actions.
The web.xml file needs to be created under the WEB-INF folder under WebContent as follows:
Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you following screen:
Now enter any word in the given text box and click Say Hello button to execute the defined action. Now if you will check the log generated, you will find following text at the bottom:
Stacking multiple Interceptors:
As you can imagine, having to configure multiple interceptor for each action would quickly become extremely unmanageable. For this reason, interceptors are managed with interceptor stacks. Here is an example, directly from the struts-default.xml file:
The above stake is called basicStack and can be used in your configuration as shown below. This configuration node is placed under the node. Each tag references either an interceptor or an interceptor stack that has been configured before the current interceptor stack. It is therefore very important to ensure that the name is unique across all interceptor and interceptor stack configurations when configuring the initial interceptors and interceptor stacks.
We have already seen how to apply interceptor to the action, applying interceptor stacks is no different. In fact, we use exactly the same tag:
The above registration of "basicStack" will register complete stake of all the six interceptors with hello action. This should be noted that interceptors are executed in the order, in which they have been configured. For example, in above case, exception will be executed first, second would be servlet-config and so on.