Struts 2 Interceptors

Interceptors are conceptually the same as servlet filters or the JDKs Proxy class. Interceptors allow for crosscutting functionality to be implemented separately from the action as well as the framework. You can achieve the following using interceptors:

  • Providing preprocessing logic before the action is called.
  • Providing postprocessing logic after the action is called.
  • Catching exceptions so that alternate processing can be performed.

Many of the features provided in the Struts2 framework are implemented using interceptors; examples include exception handling, file uploading, lifecycle callbacks and validation etc. In fact, as Struts2 bases much of its functionality on interceptors, it is not unlikely to have 7 or 8 interceptors assigned per action.

Advantage of interceptors

Pluggable If we need to remove any concern such as validation, exception handling, logging etc. from the application, we don’t need to redeploy the application. We only need to remove the entry from the struts.xml file.

Struts 2 default interceptors

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.
2) autowiring
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.
10) externalRef
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.
21) actionMappingParams
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.
27) sessionAutowiring
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 Validate able interface.
34) annotationWorkflow
35) multiselect

How to use Interceptors?

Let us see how to use an already existing interceptor to our “Hello World” program. We will use the timer interceptor whose purpose is to measure how long it took to execute an action method. Same time I’m using params interceptor whose purpose is to send the request parameters to the action. You can try your example without using this interceptor and you will find that name property is not being set because parameter is not able to reach to the action.

We will keep HelloWorldAction.java, web.xml, success.jsp and index.jsp files as they have been created in Examples chapter but let us modify the struts.xml file to add an interceptor as follows

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">
      <action name="hello" class="com.dineshonjava.struts2.action.HelloWorldAction" method="execute">
         <interceptor-ref name="params"/>
         <interceptor-ref name="timer" />
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
      </action>
   </package>
 </struts>

Execute the Application-

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/doj/. This will give you following screen:

Struts 2 Interceptors

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:

INFO: Server startup in 2135 ms
Jul 27, 2013 6:18:58 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
INFO: Executed action [//hello!execute] took 130 ms.

Here bottom line is being generated because of timer interceptor which is telling that action took total 130ms to be executed.

Create Custom Interceptors

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 following Interceptor interface:

public interface Interceptor extends Serializable{
   void destroy();
   void init();
   String intercept(ActionInvocation invocation)
   throws Exception;
}

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:

package com.dineshonjava.struts2.intercept;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author Dinesh Rajput
 *
 */
public class MyInterceptor extends AbstractInterceptor {

 private static final long serialVersionUID = 1L;

 @Override
 public String intercept(ActionInvocation invocation)throws Exception{

       /* let us do some pre-processing */
       String output = "Pre-Processing"; 
       System.out.println(output);

       /* let us call action or next interceptor */
       String result = invocation.invoke();

       /* let us do some post-processing */
       output = "Post-Processing"; 
       System.out.println(output);

       return result;
    }

}

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 diagram shows the same concept through a request flow:

Struts 2 actioninvocation

Create Action Class:

package com.dineshonjava.struts2.action;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Dinesh Rajput
 *
 */
public class HelloWorldAction extends ActionSupport {
 private static final long serialVersionUID = 4956157388836635122L;
 private String name;

    public String execute() throws Exception {
    if ("SECRET".equals(name))
       {
          return SUCCESS;
       }else{
          return ERROR;  
       }
    }  

    public String getName() {
       return name;
    }

    public void setName(String name) {
       this.name = name;
    }
}

Create a View-

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   Hello World, <s:property value="name"/>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
</head>
<body>
   <h1>Hello World From Struts2</h1>
   <form action="hello">
      <label for="name">Please enter your name</label><br/>
      <input type="text" name="name"/>
      <input type="submit" value="Say Hello"/>
   </form>
</body>
</html>

Configuration Files-

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 <interceptors>…</interceptors> tags are placed directly under the <package> 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:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">
      <interceptors>
         <interceptor name="myinterceptor" class="com.dineshonjava.struts2.intercept.MyInterceptor" />
      </interceptors>
      
      <action name="hello" class="com.dineshonjava.struts2.action.HelloWorldAction" method="execute">
         <interceptor-ref name="params"/>
         <interceptor-ref name="myinterceptor" />
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
      </action>
   </package>
 </struts>

web.xml is same as previous example.

Execute the Application-

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/doj/. This will give you following screen:

Interceptors

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:

INFO: Overriding property struts.configuration.xml.reload – old value: false new value: true
Pre-Processing
Post-Processing

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:

<interceptor-stack name="basicStack">
   <interceptor-ref name="exception"/>
   <interceptor-ref name="servlet-config"/>
   <interceptor-ref name="prepare"/>
   <interceptor-ref name="checkbox"/>
   <interceptor-ref name="params"/>
   <interceptor-ref name="conversionError"/>
</interceptor-stack>

The above stake is called basicStack and can be used in your configuration as shown below. This configuration node is placed under the <package …/> node. Each <interceptor-ref …/> 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.

<action name="hello" class="com.dineshonjava.struts2.action.HelloWorldAction" method="execute">
         <interceptor-ref name="basicStack"/>
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
      </action>

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.

 

Download Source Code
Struts2Interceptor.zip

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next

One Response

  1. afiah October 1, 2018