Method of calling Struts 2 Interceptors

Published on Author bloggerfiveLeave a comment

There are three ways to call struts2 interceptors .

We can call the struts2 interceptor before or between or after the action invoke.

Below is quick summary:

To create a Struts 2 interceptor, you need to implement Interceptor interface or extend one of the build-in interceptor class.

E.g. AbstractInterceptor

Intercept Before Action

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MyInterceptor extends AbstractInterceptor {
  private static final long serialVersionUID = 5065298925572763728L;
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
      // do something before invoke
      try{
        if(o instanceof MyAction){
          ((MyAction) o).someLogicBeforeAction();
        }
      }catch(Exception e){
        return "error";
      }
      // invocation continue   
      return invocation.invoke();
    }
  }
}

Intercept Between Action and Result

(after action is executed but before result is rendered)

Register a PreResultListener to the invocation instance. Sample code as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MyInterceptor extends AbstractInterceptor {
  private static final long serialVersionUID = 5065298925572763728L;
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
      // Register a PreResultListener and implement the beforeReslut method
      invocation.addPreResultListener(new PreResultListener() {
        @Override
        public void beforeResult(ActionInvocation invocation, String resultCode) {
          Object o = invocation.getAction();
          try{
            if(o instanceof MyAction){
              ((MyAction) o).someLogicAfterActionBeforeView();
            }
          }catch(Exception e){
            invocation.setResultCode("error");
          }
        }
      });
      
      // Invocation Continue
      return invocation.invoke();
    }
  }
}

Intercept After View Rendered

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MyInterceptor extends AbstractInterceptor {
  private static final long serialVersionUID = 5065298925572763728L;
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
      // do something before invoke
      try{
        // invocation continue   
        return invocation.invoke();
      }catch(Exception e){
        // You cannot change the result code here though, such as:
        // return "errorr";
        // This line will not work because view is already generated 
        // You can do something like database cleanup or logging at this point
        doSomeLogicAfterView();
      }
    }
  }
}

Comments

comments

Leave a Reply

Your email address will not be published. Required fields are marked *