Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The Interceptors are defined in a stack that specifies the execution order. In some cases, the order of the Interceptors on the stack can be very important.

Configuring Interceptors

Code Block
xml
xml
titlestruts.xml
<package name="default" extends="struts-default">
   <interceptors>
       <interceptor name="timer" class=".."/>
       <interceptor name="logger" class=".."/>
   </interceptors>

   <action name="login"
      class="tutorial.Login">
        <interceptor-ref name="timer"/>
        <interceptor-ref name="logger"/>
         <result name="input">login.jsp</result>
         <result name="success"
            type="redirect-action">/secure/home</result>
   </action>
</package>

Stacking Interceptors

With most web applications, we find ourselves wanting to apply the same set of Interceptors over and over again. Rather than reiterate the same list of Interceptors, we can bundle these Interceptors together using an Interceptor Stack.

...

Looking inside struts-default.xml, we can see how it's done.

The Default Configuration

Code Block
xml
xml
titlestruts.xml
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<!-- // START SNIPPET: struts-default -->
<struts>
    <package name="struts-default">
        <result-types>
            <result-type name="chain" class="com.opensymphony.xwork.ActionChainResult"/>
            <result-type name="dispatcher" class="org.apache.strutsstruts2.action2.dispatcher.ServletDispatcherResult"
                         default="true"/>
            <result-type name="freemarker" class="org.apache.strutsstruts2.action2.views.freemarker.FreemarkerResult"/>
            <result-type name="httpheader" class="org.apache.strutsstruts2.action2.dispatcher.HttpHeaderResult"/>
            <result-type name="jasper" class="org.apache.strutsstruts2.action2.views.jasperreports.JasperReportsResult"/>
            <result-type name="redirect" class="org.apache.struts.action2struts2.dispatcher.ServletRedirectResult"/>
            <result-type name="redirect-action"
                         class="org.apache.struts.action2struts2.dispatcher.ServletActionRedirectResult"/>
            <result-type name="stream" class="org.apache.strutsstruts2.action2.dispatcher.StreamResult"/>
            <result-type name="velocity" class="org.apache.strutsstruts2.action2.dispatcher.VelocityResult"/>
            <result-type name="xslt" class="org.apache.strutsstruts2.action2.views.xslt.XSLTResult"/>
        </result-types>

        <interceptors>
            <interceptor name="alias" class="com.opensymphony.xwork.interceptor.AliasInterceptor"/>
            <interceptor name="autowiring"
                         class="com.opensymphony.xwork.spring.interceptor.ActionAutowiringInterceptor"/>
            <interceptor name="chain" class="com.opensymphony.xwork.interceptor.ChainingInterceptor"/>
            <interceptor name="component" class="com.opensymphony.xwork.interceptor.component.ComponentInterceptor"/>
            <interceptor name="conversionError"
                         class="org.apache.struts.action2struts2.interceptor.WebWorkConversionErrorInterceptor"/>
            <interceptor name="external-ref" class="com.opensymphony.xwork.interceptor.ExternalReferencesInterceptor"/>
            <interceptor name="execAndWait" class="corg.apache.struts.action2struts2.interceptor.ExecuteAndWaitInterceptor"/>
            <interceptor name="exception" class="com.opensymphony.xwork.interceptor.ExceptionMappingInterceptor"/>
            <interceptor name="fileUpload" class="com.opensymphony.webwork.interceptor.FileUploadInterceptor"/>
            <interceptor name="i18n" class="com.opensymphony.xwork.interceptor.I18nInterceptor"/>
            <interceptor name="logger" class="com.opensymphony.xwork.interceptor.LoggingInterceptor"/>
            <interceptor name="model-driven" class="com.opensymphony.xwork.interceptor.ModelDrivenInterceptor"/>
            <interceptor name="params" class="com.opensymphony.xwork.interceptor.ParametersInterceptor"/>
            <interceptor name="prepare" class="com.opensymphony.xwork.interceptor.PrepareInterceptor"/>
            <interceptor name="static-params" class="com.opensymphony.xwork.interceptor.StaticParametersInterceptor"/>
            <interceptor name="servlet-config" class="org.apache.struts.action2.interceptor.ServletConfigInterceptor"/>
            <interceptor name="sessionAutowiring"
                         class="org.apache.strutsstruts2.action2.spring.interceptor.SessionContextAutowiringInterceptor"/>
            <interceptor name="timer" class="com.opensymphony.xwork.interceptor.TimerInterceptor"/>
            <interceptor name="token" class="com.opensymphony.webwork.interceptor.TokenInterceptor"/>
            <interceptor name="token-session"
                         class="com.opensymphony.webwork.interceptor.TokenSessionStoreInterceptor"/>
            <interceptor name="validation" class="com.opensymphony.xwork.validator.ValidationInterceptor"/>
            <interceptor name="workflow" class="com.opensymphony.xwork.interceptor.DefaultWorkflowInterceptor"/>

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

            <!-- Sample validation and workflow stack -->
            <interceptor-stack name="validationWorkflowStack">
                <interceptor-ref name="basicStack"/>
                <interceptor-ref name="validation"/>
                <interceptor-ref name="workflow"/>
            </interceptor-stack>

            <!-- Sample file upload stack -->
            <interceptor-stack name="fileUploadStack">
                <interceptor-ref name="fileUpload"/>
                <interceptor-ref name="basicStack"/>
            </interceptor-stack>

            <!-- Sample WebWorkmodel-driven Inversionstack of Control stack -->
            <interceptor-stack name="modelDrivenStack">
    Note: WebWork's IoC is deprecated - please
                 look at alternatives such as Sprint -->
            <interceptor-stackref name="componentStack">
                <interceptor-ref name="componentmodel-driven"/>
                <interceptor-ref name="basicStack"/>
            </interceptor-stack>

            <!-- Sample model-drivenaction chaining stack  -->
            <interceptor-stack name="modelDrivenStackchainStack">
                <interceptor-ref name="model-drivenchain"/>
                <interceptor-ref name="basicStack"/>
            </interceptor-stack>

            <!-- Sample actioni18n chaining stack -->
            <interceptor-stack name="chainStack">
                <interceptor-ref name="chaini18n"/>
                <interceptor-ref name="basicStack"/>
            </interceptor-stack>

            <!-- Sample execute i18n stackand wait stack.
                 Note: execAndWait should always be the *last* interceptor. -->
            <interceptor-stack name="chainStackexecuteAndWaitStack">
                <interceptor-ref name="i18nbasicStack"/>
                <interceptor-ref name="basicStackexecAndWait"/>
            </interceptor-stack>

            <!-- SampleA executecomplete and wait stackstack with all the common interceptors in place.
                 Note: execAndWaitGenerally, this stack should always be the *last* interceptor. -->
  one you use, though it
          <interceptor-stack name="executeAndWaitStack">
      may process additional stuff you don't need, which could
  <interceptor-ref name="basicStack"/>
              lead  <interceptor-ref name="execAndWait"/>
     to some performance problems. Also, the ordering can be
       </interceptor-stack>

          switched  <!-- A complete stack with all the common interceptors in place.
around (ex: if you wish to have your components
                 before prepare() is Generallycalled, thisyou'd stackneed shouldto bemove the onecomponent
    you use, though it
          interceptor up -->
     may process additional stuff you don't need, which could<interceptor-stack name="defaultStack">
                 lead to some performance problems. Also, the ordering can be
<interceptor-ref name="exception"/>
                <interceptor-ref name="alias"/>
          switched around (ex: if you wish to have your components<interceptor-ref name="prepare"/>
                 before prepare() is called, you'd need to move the component
<interceptor-ref name="servlet-config"/>
                <interceptor-ref name="i18n"/>
        interceptor up -->
            <interceptor-stackref name="defaultStackchain"/>
                <interceptor-ref name="exceptionmodel-driven"/>
                <interceptor-ref name="aliasfileUpload"/>
                <interceptor-ref name="preparestatic-params"/>
                <interceptor-ref name="servlet-configparams"/>
                <interceptor-ref name="i18nconversionError"/>
                <interceptor-ref name="chainvalidation"/>
                <interceptor-ref name="model-drivenworkflow"/>
            </interceptor-stack>

    <interceptor-ref name="fileUpload"/>
       <!-- The completeStack is here for backwards compatibility for
 <interceptor-ref name="static-params"/>
               applications <interceptor-ref name="params"/>
that still refer to the defaultStack by the
                 <interceptor-refold name="conversionError"/ -->
                <interceptor-refstack name="validationcompleteStack"/>
                <interceptor-ref name="workflowdefaultStack"/>
            </interceptor-stack>

        </interceptors>

    <!-- The completeStack is here for backwards compatibility for<default-interceptor-ref name="defaultStack"/>
                 applications that still refer to the defaultStack by the
                 old name -->
            <interceptor-stack name="completeStack">
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>

        <default-interceptor-ref name="defaultStack"/>
    </package>
</xwork>
<!-- // END SNIPPET: struts-default -->

Since we included struts-default.xml in our struts.xml, all the predefined interceptors and stacks are available for us to use in our actions.

timer

clocks how long the action (including nested interceptors and view) takes to execute

logger

logs the action being executed

chain

makes the previous action's properties available to the current action. Used to make action chaining (reference: Result Types)

static-params

sets the parameters defined in struts.xml onto the action. These are the <param /> tags that are direct children of the <action /> tag

params

sets the request (POST and GET) parameters onto the action class. We have seen an example of this in TODO

model-driven

if the action implements ModelDriven, pushes the getModel() result onto the Value Stack

component

enables and makes registered components available to the actions.

token

checks for valid token presence in action, prevents duplicate form submission

token-session

same as above, but storing the submitted data in session when handed an invalid token;

validation

performs validation using the validators defined in {Action}-validation.xml (reference: Validation).

workflow

calls the validate method in your action class. If action errors created then it returns the INPUT view. Good to use together with the validation interceptor (reference: Validation)

servlet-config

give access to HttpServletRequest and HttpServletResponse (think twice before using this since this ties you to the Servlet API)

prepare

allows you to programmatic access to your Action class before the parameters are set on it.

conversionError

Adds field errors if any type-conversion errors occurred\

execAndWait

Spawns a separate thread to execute the action

fileUpload

Sets uploaded files as action files (File objects)

In addition to the prepackaged Interceptors, struts-default.xml includes prepackaged combinations in named Interceptor Stacks.

Building Your Own Interceptor

If the stock Interceptors aren't enough, you can implement custom Interceptors to solve a new problem or and old problem differently.

Suppose several pages in an application would like to to display a greeting that changes according to the time of day. A good way to solve this use case is to use an Interceptor to place the greeting in the session on each request. As soon as the time of day changes, so would the greeting. As an Interceptor, the greeting can be created automatically, so that the Actions need not be bothered.

Implementing a Greeting Interceptor

  1. Create an Interceptor class by implementing the com.opensymphony.xwork.interceptor.Interceptor interface (bundled in the xwork-1.1.jar provided with the framework distribution).
  2. Declare the class in your XML configuration file (struts.xml) using the element <interceptor /> nested within <interceptors />.
  3. Create stacks of Interceptors, using the <interceptor-stack /> element (optional).
  4. Determine which Interceptors are used by which mapping, using <interceptor-ref /> or <default-interceptor-ref />. The <interceptor-ref> defines the interceptors to be used in a specific action. The <default-interceptor-ref /> determines the default interceptor stack to be used by all actions that do not specify their own <interceptor-ref />.

Coding the Interceptor class

...


package tutorial;

import java.util.Calendar;
import com.opensymphony.xwork.interceptor.Interceptor;
import com.opensymphony.xwork.ActionInvocation;

public class GreetingInterceptor implements Interceptor {
  public void init() { }
  public void destroy() { }
  public String intercept(ActionInvocation invocation) throws Exception {
    Calendar calendar = Calendar.getInstance();
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    String greeting = (hour < 6) ? "Good evening" :
        ((hour < 12) ? "Good morning":
    ((hour < 18) ? "Good afternoon": "Good evening"));

     invocation.getInvocationContext().getSession().put("greeting", greeting);

     String result = invocation.invoke();

     return result;
  }
}

Coding the configuration

...


<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
  <include file="struts-default.xml" />

  <package name="default" extends="struts-default">
     <interceptors>
       <interceptor name="greeting" class="tutorial.GreetingInterceptor" />
     </interceptors>

     <action name="greeting" class="tutorial.GreetingAction">
    <interceptor-ref name="greeting" />
    <result name="success" type="velocity">greeting.vm</result>
      </action>

      <!-- other action mappings -->

   </package>
 </struts>

Coding the Action class

...


package tutorial;

import com.opensymphony.xwork.ActionSupport;

public class GreetingAction extends ActionSupport {
  public String execute() throws Exception
  {
    return SUCCESS;
  }
}

Coding the result page

...

</package>
</struts>
<!-- // END SNIPPET: struts-default -->

By including, struts-default.xml in an application's struts.xml, we make all the predefined interceptors and stacks available.

Framework Interceptors

Interceptor classes are also defined using a key-value pair specified in the Struts configuration file. The names specified below come specified in struts-default.xml. If you extend the struts-default package, then you can use the names below. Otherwise, they must be defined in your package with a name-class pair specified in the <interceptors> tag.

Interceptor

Name

Description

Alias Interceptor

alias

Converts similar parameters that may be named differently between requests.

Chaining Interceptor

chain

Makes the previous Action's properties available to the current Action. Commonly used together with <result type="chain"> (in the previous Action).

Conversion Error Interceptor

conversionError

Adds conversion errors from the ActionContext to the Action's field errors

Create Session Interceptor

createSession

Create an HttpSession automatically, useful with certain Interceptora that require a HttpSession to work properly (like the TokenInterceptor)

Execute and Wait Interceptor

execAndWait

Executes the Action in the background and then sends the user off to an intermediate waiting page.

Exception Interceptor

exception

Maps exceptions to a result.

File Upload Interceptor

fileUpload

An Interceptor that adds easy access to file upload support.

I18n Interceptor

i18n

Remembers the locale selected for a user's session.

Logger Interceptor

logger

Outputs the name of the Action.

Message Store Interceptor

store

Store and retrieve action messages / errors / field errors for action that implements ValidationAware interface into session.

Model Driven Interceptor

model-driven

If the Action implements ModelDriven, pushes the getModel Result onto the Value Stack.

Parameters Interceptor

params

Sets the request parameters onto the Action.

Prepare Interceptor

prepare

If the Action implements Preparable, calls its prepare method.

Scope Interceptor

scope

Simple mechanism for storing Action state in the session or application scope.

Servlet Config Interceptor

servlet-config

Provide access to Maps representing HttpServletRequest and HttpServletResponse.

Static Parameters Interceptor

static-params

Sets the struts.xml defined parameters onto the action. These are the <param> tags that are direct children of the <action> tag.

Timer Interceptor

timer

Outputs how long the Action takes to execute (including nested Interceptors and View)

Token Interceptor

token

Checks for valid token presence in Action, prevents duplicate form submission.

Token Session Interceptor

token-session

Same as Token Interceptor, but stores the submitted data in session when handed an invalid token

Validation Interceptor

validation

Performs validation using the validators defined in action-validation.xml

Workflow Interceptor

workflow

Calls the validate method in your Action class. If Action errors are created then it returns the INPUT view.

Parameter Filter Interceptor

N/A

Removes parameters from the list of those available to Actions

Method Filtering

Wiki Markup
{snippet:id=javadoc|javadoc=true|url=com.opensymphony.xwork.interceptor.MethodFilterInterceptor}

Interceptor Parameter Overriding

Wiki Markup
{snippet:id=parameterOverriding|javadoc=true|url=com.opensymphony.xwork.interceptor.Interceptor}

Order of Interceptor Execution

Interceptors provide an excellent means to wrap before/after processing. The concept reduces code duplication (think AOP).

Code Block

<interceptor-stack name="xaStack">
  <interceptor-ref name="thisWillRunFirstInterceptor"/>
  <interceptor-ref name="thisWillRunNextInterceptor"/>
  <interceptor-ref name="followedByThisInterceptor"/>
  <interceptor-ref name="thisWillRunLastInterceptor"/>
</interceptor-stack>

(warning) Note that some Interceptors will interrupt the stack/chain/flow ... so the order is very important.

Interceptors implementing com.opensymphony.xwork.interceptor.PreResultListener will run after the Action executes but before the Result executes.

Code Block

thisWillRunFirstInterceptor
  thisWillRunNextInterceptor
    followedByThisInterceptor
      thisWillRunLastInterceptor
        MyAction1
        MyAction2 (chain)
        MyPreResultListener
        MyResult (result)
      thisWillRunLastInterceptor
    followedByThisInterceptor
  thisWillRunNextInterceptor
thisWillRunFirstInterceptor

FAQ

Next: Result Types

...


<html>
  <head>
    <title>Understanding Interceptors</title>
   </head>
   <body>
     #set ($ses = $req.getSession())
     <p><b>${ses.getAttribute('greeting')}!</b></p>
   </body>
 </html>

How the code works

Let's take a look at our Interceptor class first. An Interceptor must implement com.opensymphony.xwork.interceptor.Interceptor which expects three methods.

  • init() is called during interceptor initialization,
  • destroy() is called during destruction, and most importantly,
    • intercept(ActionInvocation invocation) is where we place the code that does the work.

The Greeting Interceptor returns the result from invocation.invoke. The invokemethod executes the next Interceptor in the stack or, if this is the last Interceptor, the appropriate method of the Action class. The invokemethod grants the Interceptor the power to short-circuiting the Action Invocation. Instead of calling invoke, the Interceptor can return a result String and bypass any remaining Interceptors on the stack and the Action's execute method.

An Interceptor can also execute code after the Action method executes. Just place more code after the invocation.invoke call. Control returns to each Interceptor on the stack in reverse order. When the call to invoke returns, you can continue processing.

Many Interceptors execute code only before or after the Action, but some do execute code in both places. To make coding Interceptors a little easier, the framework provides an abstract class that implements the "before and after" behaviour. Instead of calling invoke}] itself, an Interceptor can extend {{com.opensymphony.xwork.interceptor.AroundInterceptor and implement the methods before(ActionInvocation invocation) and after(ActionInvocation dispatcher, String result).

Summary

The Interceptor strategy promotes reusability and simplicity. Interceptors make it easier to separate concerns, so that we can solve one problem at a time. The best part is that each application, and each Action, controls exactly what Interceptors are used in what order.

...

Next

...

Onward to Understanding Validation

...

Prev

...