<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<p>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:</p>
<ul style="text-align: left;">
<li>Providing <b>preprocessing </b>logic before the action is called.</li>
<li>Providing <b>postprocessing </b>logic after the action is called.</li>
<li>Catching exceptions so that alternate processing can be performed.</li>
</ul>
<p>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.</p>
<h2><b>Advantage of interceptors</b></h2>
<p><b>Pluggable</b> If we need to remove any concern such as validation, exception handling, logging etc. from the application, we don&#8217;t need to redeploy the application. We only need to remove the entry from the struts.xml file.</p>
<h2><b>Struts 2 default interceptors</b></h2>
<p>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:<br />
<b>1) alias</b> It converts similar parameters that have different names between requests.<br />
<b>2) autowiring</b><br />
<b>3) chain</b> If it is used with chain result type, it makes the properties of previous action available in the current action.<br />
<b>4) checkbox</b> It is used to handle the check boxes in the form. By this, we can detect the unchecked checkboxes.<br />
<b>5) cookie</b> It adds a cookie to the current action.<br />
<b>6) conversionError</b> It adds conversion errors to the action&#8217;s field errors.<br />
<b>7) createSession</b> It creates and HttpSession object if it doesn&#8217;t exists.<br />
<b>8) clearSession</b> It unbinds the HttpSession object.<br />
<b>9) debugging</b> It provides support of debugging.<br />
<b>10) externalRef</b><br />
<b>11) execAndWait</b> It sends an intermediate waiting page for the result.<br />
<b>12) exception</b> It maps exception to a result.<br />
<b>13) fileUpload</b> It provides support to file upload in struts 2.<br />
<b>14) i18n</b> It provides support to internationalization and localization.<br />
<b>15) jsonValidation</b> It provides support to asynchronous validation.<br />
<b>16) logger</b> It outputs the action name.<br />
<b>17) store</b> It stores and retrieves action messages, action errors or field errors for action that implements ValidationAware interface.<br />
<b>18) modelDriven</b> It makes other model object as the default object of valuestack.<br />
<b>19) scopedModelDriven</b> It is similar to ModelDriven but works for action that implements ScopedModelDriven.<br />
<b>20) params</b> It populates the action properties with the request parameters.<br />
<b>21) actionMappingParams</b><br />
<b>22) prepare</b> It performs preparation logic if action implements Preparable interface.<br />
<b>23) profiling</b> It supports action profiling.<br />
<b>24) roles</b> It supports role-based action.<br />
<b>25) scope</b> It is used to store the action state in the session or application scope.<br />
<b>26) servletConfig</b> It provides access to maps representing HttpServletRequest and HttpServletResponse.<br />
<b>27) sessionAutowiring</b><br />
<b>28) staticParams</b> It maps static properties to action properties.<br />
<b>29) timer</b> It outputs the time needed to execute an action.<br />
<b>30) token</b> It prevents duplication submission of request.<br />
<b>31) tokenSession</b> It prevents duplication submission of request.<br />
<b>32) validation</b> It provides support to input validation.<br />
<b>33) workflow</b> It calls the validate method of action class if action class implements Validate able interface.<br />
<b>34) annotationWorkflow</b><br />
<b>35) multiselect</b></p>
<div id="ads-id" align="center"></div>
<h2><b>How to use <i>Interceptors</i>?</b></h2>
<p>Let us see how to use an already existing interceptor to our &#8220;Hello World&#8221; program. We will use the timer interceptor whose purpose is to measure how long it took to execute an action method. Same time I&#8217;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.</p>
<p>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</p>
</div>
<pre class="highlight"><;?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>; 
</pre>
</div>
<h2><b>Execute the Application-</b></h2>
<p>Right click on the project name and click <b>Export >; WAR</b> File to create a War file. Then deploy this WAR in the Tomcat&#8217;s webapps directory. Finally, start Tomcat server and try to access<br />
URL <i><b>http://localhost:8080/doj/. </b></i>This will give you following screen:</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/07/9999.png" border="0" /></div>
<p>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:</p>
<div style="background-color: #ff99cc;">INFO: Server startup in 2135 ms<br />
Jul 27, 2013 6:18:58 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info<br />
INFO: Executed action [//hello!execute] took 130 ms.</div>
<p>Here bottom line is being generated because of timer interceptor which is telling that action took total 130ms to be executed.</p>
<h2><b>Create Custom <i>Interceptors</i>&#8211;</b></h2>
<p>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:</p>
</div>
<pre class="highlight">public interface Interceptor extends Serializable{ 
 void destroy(); 
 void init(); 
 String intercept(ActionInvocation invocation) 
 throws Exception; 
} 
</pre>
<p>As the names suggest, the <b>init(</b>) method provides a way to initialize the interceptor, and the<b> destroy() </b>method provides a facility for interceptor cleanup. Unlike actions, interceptors are reused across requests and need to be thread-safe, especially the <b>intercept()</b> method.</p>
<p>The <b>ActionInvocation </b>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.</p>
<p>If you have no need for initialization or cleanup code, the <b>AbstractInterceptor </b>class can be extended. This provides a default no-operation implementation of the <b>init() and destroy() </b>methods.</p>
<h2><b>Create <i>Interceptor </i>Class:</b></h2>
<p>Let us create following<i><b> MyInterceptor.java</b></i> in <b>Java Resources >; src</b> folder:</p>
</div>
<pre class="highlight">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; 
 } 
 
} 
 
</pre>
<p>As you notice, actual action will be executed using the interceptor by<b><i> invocation.invoke()</i></b> call. So you can do some <b>pre-processing</b> and some <b>post-processing</b> based on your requirement.</p>
<p>The framework itself starts the process by making the first call to the <b>ActionInvocation </b>object&#8217;s <b>invoke()</b>. Each time<b> invoke() </b>is called, <b>ActionInvocation </b>consults its state and executes whichever interceptor comes next. When all of the configured interceptors have been invoked, the<b> invoke()</b> method will cause the action itself to be executed. Following diagram shows the same concept through a request flow:</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/07/actioninvocation.jpg" border="0" /></div>
</div>
<h2><b>Create Action Class:</b></h2>
<pre class="highlight">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; 
 } 
} 
</pre>
<h2><b>Create a View-</b></h2>
<pre class="highlight"><;%@ 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>; 
</pre>
</div>
<pre class="highlight"><;%@ 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>; 
</pre>
<h2><b>Configuration Files-</b></h2>
<p>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<b> <;interceptors>;&#8230;<;/interceptors>;</b> tags are placed directly under the <b><;package>;</b> tag ins <i><b>struts.xml</b></i> 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:</p>
</div>
<pre class="highlight"><;?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>; 
</pre>
<p><b>web.xml is same as previous example.</b></p>
<h3><b>Execute the Application-</b></h3>
<p>Right click on the project name and click <b>Export >; WAR</b> File to create a War file. Then deploy this WAR in the Tomcat&#8217;s webapps directory. Finally, start Tomcat server and try to access<br />
URL <i><b>http://localhost:8080/doj/. </b></i>This will give you following screen:</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/07/9999.png" border="0" /></div>
<p>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:</p>
<div style="background-color: #ff99cc;">INFO: Overriding property struts.configuration.xml.reload &#8211; old value: false new value: true<br />
Pre-Processing<br />
Post-Processing</div>
</div>
<h2><b>Stacking multiple Interceptors:</b></h2>
<p>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<i><b> struts-default.xml</b></i> file:</p>
<pre class="highlight"><;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>; 
</pre>
<p>The above stake is called <i><b>basicStack </b></i>and can be used in your configuration as shown below. This configuration node is placed under the <b><;package &#8230;/>;</b> node. Each <b><;interceptor-ref &#8230;/>;</b> 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.</p>
<pre class="highlight"><;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>;</pre>
<p>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:</p>
<p>The above registration of &#8220;basicStack&#8221; 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.</p>
</div>
<p> ;</p>
</div>
<h3><b>Download Source Code</b><br />
<b><a href="https://sites.google.com/a/dineshonjava.com/dineshonjava/dineshonjava/Struts2Interceptor.zip?attredirects=0&;d=1" target="_blank" rel="noopener">Struts2Interceptor.zip</a></b></h3>
<p> ;</p>
<div style="background-color: pink; border-width: thin; text-align: center;"><b><;<;<a href="https://dineshonjava.com/2013/07/struts-2-actions.html#.UfOTfG2ktH0">Previous</a> <;<; || <a href="https://dineshonjava.com/2013/07/struts-2-baby-step-to-learn.html">Index </a>|| >;>;<a href="https://dineshonjava.com/2013/07/struts-2-result-types.html">Next</a> >;>;</b></div>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/struts-2-actions/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/struts-2-result-types/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '387'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…