Struts 2 Custom Interceptor Example

Generally, the default interceptors are sufficient for most applications, however, we can still create our own interceptor when we need to implement more specific action processing.

In this example, we are going to see how to write a custom interceptor and configure it to process our Struts action.


 1. Project structure



2. Action class

We are going to intercept the execution of execute() method to inject additional action processing (println(..)) before and after the method call:


3. Create interceptor class

To create a custom interceptor, we need to implement the com.opensymphony.xwork2.interceptor.Interceptor interface as follows:

We have overridden three methods:

  • init: it is called after the interceptor is initialized.
  • intercept: it is called each time the action is invoked, we can use it to add specific processing before and after the action execution.
  • destroy: it is called before the interceptor is destroyed.

How does it work? When we make a request for the UserAction:

  • The intercept method is called
  • Struts passes the execution state of the UserAction (represented by the ActionInvocation interface) to the intercept method.
  • The interceptor calls the invoke method to let the execution chain proceed to the next level.
  • Return the result of the action execution


4. struts.xml

In order to register our custom interceptor for the UserAction, we create a custom stack to which we add our interceptor (and the defaultStack), and we add reference to the stack in our action definition:


5. Test It

Open the browser and type in : http://localhost:8080/Struts2CustomInterceptorExample/


Enter a name and click the submit button:


Let’s see what happens in the console :


Download source code