Child pages
  • Building Your Own Interceptor
Skip to end of metadata
Go to start of metadata

Building your own Interceptor

If none of the above interceptors suit your particular need, you will have to implement your own interceptor. Fortunately, this is an easy task to accomplish. Suppose we need an interceptor that places a greeting in the Session according to the time of the day (morning, afternoon or evening). Here's how we could implement it:



Let's take a look at our interceptor class first. As explained before, the interceptor must implement com.opensymphony.xwork.interceptor.Interceptor's methods: init(), called during interceptor initialization, destroy(), called during destruction, and most importantly, intercept(ActionInvocation invocation), which is where we place the code that does the work.

Notice that our interceptor returns the result from invocation.invoke() which is the method responsible for executing the next interceptor in the stack or, if this is the last one, the action. This means that the interceptor has the power of short-circuiting the action invocation and return a result string without executing the action at all! Use this with caution, though.

One other thing that interceptors can do is execute code after the action has executed. To do that, just place code after the invocation.invoke() call.

The struts.xml configuration and the result page are pretty straightforward and require no further explanation. A custom Action is not neede for this example, so we omit the class reference, and use the default ActionSupport class.

  • No labels

1 Comment

  1. this is wrong:
    import org.apache.struts2.ActionInvocation;

    i have changed with:
    import com.opensymphony.xwork2.ActionInvocation; and it works