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
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:
Let us create following MyInterceptor.java in Java Resources > src folder:
Let us create a java file HelloWorldAction.java under Java Resources > src with a package namecom.tutorialspoint.struts2 with the contents given below.
Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project.
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.
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
It should be noted that you can register more than one interceptors inside
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:
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: