Struts Interceptor

Struts Interceptors are widely used in struts application to intercept the requests that needs to be processed.Interceptors are a type of object that helps to intercepts an action dynamically. In Struts we can use a mechanism of controlling a request using interceptors and the interceptors are responsible for the most of the request process. It is executed before and after the action execution and permits the developers to write the code which can execute and after the action. The interceptors restrict an action before execution. Interceptors handle the following task.

  1. Logging
  2. Validation
  3. File Upload
  4. Double-submit guard etc
Struts Interceptors
Struts Interceptors

Interceptor’s action life cycle: – Interceptors execute the code before and after an action is invoked. The main steps of the action life cycle are,

  1. ServletDispatch instantiates a new ActionProxy and calls execute().
  2. Interceptors intercept the request being sent to and returning from the action.
  3. Once execution of the action is complete the request is sent to a result to render the result.
Steps needed for struts interceptor action
Steps needed for struts interceptor action

Steps needed for struts interceptor actions

  1. Request is generated by user and sent to Servlet container.
  2. Servlet container invokes FilterDispatcher filter which in turn determines appropriate action.
  3. One by one Intercetors are applied before calling the Action. Interceptors perform tasks such as Logging, Validation, File Upload, Double-submit guard etc.
  4. Action is executed and the Result is generated by Action.
  5. The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.

Interceptor’s configuration: –

Eg: – struts.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=“redirectAction”>/secure/home</result>
</action>
</package>

Stacking interceptors: –

We can apply the same set of interceptors over and over again.

Eg: –

<package name=“default” extends=“struts-default”>
<interceptors>
<interceptor name=“timer” class=“..”/>
<interceptor name=“logger” class=“..”/>
<interceptor-stack name=“myStack”>
<interceptor-ref name=“timer”/>
<interceptor-ref name=“logger”/>
</interceptor-stack>
</interceptors>

<action name=“login”
class=“tutuorial.Login”>
<interceptor-ref name=“myStack”/>
<result name=“input”>login.jsp</result>
<result name=“success”
type=“redirectAction”>/secure/home</result>
</action>
</package>

The default configuration is: –

<!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.j2eebrain.ActionChainResult”/>
<result-type
name=“dispatcher” class=“org.apache.struts.action2.dispatcher.ServletDispatcherResult”
default=“true”/>
<result-type
name=“freemarker” class=“org.apache.struts.action2.views.freemarker.FreemarkerResult”/>
<result-type
name=“httpheader” class=“org.apache.struts.action2.dispatcher.HttpHeaderResult”/>
<result-type
name=“jasper” class=“org.apache.struts.action2.views.jasperreports.JasperReportsResult”/>
<result-type
name=“redirect” class=“org.apache.struts.action2.dispatcher.ServletRedirectResult”/>
<result-type name=“redirect-action”
class=“org.apache.struts.action2.dispatcher.ServletActionRedirectResult”/>
<result-type name=“stream” class=“org.apache.struts.action2.dispatcher.StreamResult”/>
<result-type
name=“velocity” class=“org.apache.struts.action2.dispatcher.VelocityResult”/>
<result-type name=“xslt” class=“org.apache.struts.action2.views.xslt.XSLTResult”/>
</result-types>

<interceptors>
<interceptor
name=“alias” class=“com.j2eebrain.interceptor.AliasInterceptor”/>
<interceptor name=“autowiring
class=“com.j2eebrain.spring.interceptor.ActionAutowiringInterceptor”/>
<interceptor
name=“chain” class=“com.j2eebrain.interceptor.ChainingInterceptor”/>
<interceptor
name=“component” class=“com.j2eebrain.interceptor.component.ComponentInterceptor”/>
<interceptor name=“conversionError”
class=“org.apache.struts.action2.interceptor.WebWorkConversionErrorInterceptor”/>
<interceptor
name=“external-ref” class=“com.j2eebrain.interceptor.ExternalReferencesInterceptor”/>
<interceptor
name=“execAndWait” class=“corg.apache.struts.action2.interceptor.ExecuteAndWaitInterceptor”/>
<interceptor
name=“exception” class=“com.j2eebrain.interceptor.ExceptionMappingInterceptor”/>
<interceptor
name=“fileUpload” class=“com.opensymphony.webwork.interceptor.FileUploadInterceptor”/>
<interceptor
name=“i18n” class=“com.j2eebrain.interceptor.I18nInterceptor”/>
<interceptor
name=“logger” class=“com.j2eebrain.interceptor.LoggingInterceptor”/>
<interceptor
name=“model-driven” class=“com.j2eebrain.interceptor.ModelDrivenInterceptor”/>
<interceptor
name=“params” class=“com.j2eebrain.interceptor.ParametersInterceptor”/>
<interceptor
name=“prepare” class=“com.j2eebrain.interceptor.PrepareInterceptor”/>
<interceptor
name=“static-params” class=“com.j2eebrain.interceptor.StaticParametersInterceptor”/>
<interceptor
name=“servlet-config” class=“org.apache.struts.action2.interceptor.ServletConfigInterceptor”/>
<interceptor name=“sessionAutowiring”
class=“org.apache.struts.action2.spring.interceptor.SessionContextAutowiringInterceptor”/>
<interceptor
name=“timer” class=“com.j2eebrain.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.j2eebrain.validator.ValidationInterceptor”/>
<interceptor
name=“workflow” class=“com.j2eebrain.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 WebWork Inversion of Control stack

Note: WebWork’s IoC is deprecated – please look at alternatives such as Sprint –>

<interceptor-stack name=“componentStack>
<interceptor-ref name=“component”/>
<interceptor-ref name=“basicStack”/>
</interceptor-stack>
<!-- Sample model-driven stack  -->
<interceptor-stack name=“modelDrivenStack”>
<interceptor-ref name=“model-driven”/>
<interceptor-ref name=“basicStack”/>
</interceptor-stack>
<!-- Sample action chaining stack -->
<interceptor-stack name=“chainStack”>
<interceptor-ref name=“chain”/>
<interceptor-ref name=“basicStack”/>
</interceptor-stack>
<!-- Sample i18n stack -->
<interceptor-stack name=“chainStack”>
<interceptor-ref name=“i18n”/>
<interceptor-ref name=“basicStack”/>
</interceptor-stack>
<!-- Sample executes and wait stack.
Note: execAndWait should always be the *last* interceptor. -->
<interceptor-stack name=“executeAndWaitStack”>
<interceptor-ref name=“basicStack”/>
<interceptor-ref name=“execAndWait”/>
</interceptor-stack>
<!-- A complete stack with all the common interceptors in place. Generally, this stack should be the one you use, though it may process additional stuff you don’t need, which could lead to some performance problems. Also, the ordering can be switched around (ex: if you wish to have your components before prepare() is called, you’d need to move the component   interceptor up -->
<interceptor-stack name=“defaultStack”>
<interceptor-ref name=“exception”/>
<interceptor-ref name=“alias”/>
<interceptor-ref name=“prepare”/>
<interceptor-ref name=“servlet-config”/>
<interceptor-ref name=“i18n”/>
<interceptor-ref name=“chain”/>
<interceptor-ref name=“model-driven”/>
<interceptor-ref name=“fileUpload”/>
<interceptor-ref name=“static-params”/>
<interceptor-ref name=“params”/>
<interceptor-ref name=“conversionError”/>
<interceptor-ref name=“validation”/>
<interceptor-ref name=“workflow”/>
</interceptor-stack>

<!-- The completeStack is here for backwards compatibility for 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 valuators 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)

Commonly used framework interceptors

1)      Alias Interceptor: – Converts similar parameters that may be named differently between requests.

2)      Chaining Interceptor: – Makes the previous Action’s properties available to the current Action. Commonly used together with <result type=“chain”> (in the previous Action).

3)      Checkbox Interceptor: – Adds automatic checkbox handling code that detects an unchecked checkbox and add it as a parameter with a default (usually ‘false’) value. Uses a specially named hidden field to detect unsubmitted checkboxes. The default unchecked value is overridable for non-boolean value’d checkboxes.

4)      Cookie Interceptor: – Inject cookie with a certain configurable name / value into action. (Since 2.0.7.)

5)      Conversion Error Interceptor: – Adds conversion errors from the ActionContext to the Action’s field errors

6)      Create Session Interceptor: – Create an HttpSession automatically, useful with certain Interceptors that require a HttpSession to work properly (like the TokenInterceptor)

7)      DebuggingInterceptor: – Provides several different debugging screens to provide insight into the data behind the page.

8)      Execute and Wait Interceptor: – Executes the Action in the background and then sends the user off to an intermediate waiting page.

9)      Exception Interceptor: – Maps exceptions to a result.

10)  File Upload Interceptor: – An Interceptor that adds easy access to file uploads support.

11)  I18n Interceptor: – Remembers the locale selected for a user’s session.

12)  Logger Interceptor: – Outputs the name of the Action.

13)  Message Store Interceptor: – Store and retrieve action messages / errors / field errors for action that implements ValidationAware interface into session.

14)  Model Driven Interceptor: – If the Action implements ModelDriven, pushes the getModel Result onto the Value Stack.

15)  Scoped Model Driven Interceptor: – If the Action implements ScopedModelDriven, the interceptor retrieves and stores the model from a scope and sets it on the action calling setModel.

16)  Parameters Interceptor: – Sets the request parameters onto the Action.

17)  Prepare Interceptor: – If the Action implements Preparable, calls it’s prepare method.

18)  Scope Interceptor: – Simple mechanism for storing Action state in the session or application scope.

19)  Servlet Config Interceptor: – Provide access to Maps representing HttpServletRequest and HttpServletResponse.

20)  Static Parameters Interceptor: – Sets the struts.xml defined parameters onto the action. These are the <param> tags that are direct children of the <action> tag.

21)  Roles Interceptor: – Action will only be executed if the user has the correct JAAS role.

22)  Timer Interceptor: – Outputs how long the Action takes to execute (including nested Interceptors and View)

23)  Token Interceptor: – Checks for valid token presence in Action, prevents duplicate form submission.

24)  Token Session Interceptor: – Same as Token Interceptor, but stores the submitted data in session when handed an invalid token

25)  Validation Interceptor: – Performs validation using the validators defined in action-validation.xml

26)  Workflow Interceptor: – Calls the validate method in your Action class. If Action errors are created then it returns the INPUT view.

27)  Parameter Filter Interceptor: – Removes parameters from the list of those available to Actions

28)  Profiling Interceptor: – Activate profiling through parameter

29)  Multiselect Interceptor: – Like the checkbox interceptor detects that no value was selected for a field with multiple values (like a select) and adds an empty parameter

 

The struts2 interceptor is widely used in struts application .