Struts 2 Default Interceptors Example

 

In Struts 2, interceptor is a component that can be plugged in easily to add more processing to the action objects.

An interceptor is applied to an action and must be registered in the configuration file.

An interceptor runs before or/and after the action it is registered for.

Struts 2 provides a list of default interceptors. In this example we will see three examples :

  • params : to populate the action’s properties with the request parameters.
  • timer : to output the time needed to execute an action.
  • logger : to output the action name.

 

 1. Project structure

Struts2DefaultInterceptorsExample

 

2. JSP views

index.jsp : a simple form with an input text field and submit button.

welcome.jsp : used to display the username submitted value.

 

3. Action class

 

4. struts.xml

To apply the three interceptors on our two actions index and user, we will process as following :

Create an interceptor stack myStack that groups our three interceptors, then apply it to both actions by using the interceptor-ref element under the action element of each action.

The order of appearance of interceptors in the stack is important, because it determines the order of invocation of these interceptors for each action.

Notice that when we extend the struts-default package, then we can use all Struts 2 default interceptors. But once we declare our own stack, we can no longer use the default interceptors, unless we include the defaultStack in our own stack as shown below.

 

5. Test It

Open the browser and type : localhost:8080/Struts2DefaultInterceptorsExample/index.action

Struts2DefaultInterceptorsExample-2

Enter a name and click the submit button

Struts2DefaultInterceptorsExample-3

 

Let see now what happens in the console :

That shows the result of using the two interceptors : logger and timer

To test the params intercepter, exclude it from myStack in struts.xml, then restart Tomcat and test again, we will have something like this :

Struts2DefaultInterceptorsExample-4

Why?? …The property username wasn’t populated because we have deactivated the params interceptor.

 

Download source code