Thursday, January 2, 2014

How to configure Interceptor in Struts2

1) Do following configuration in struts.xml
        <!--If Single interceptor -->
        <struts>
                <package name="default" namespace="/" extends="struts-default" >
                        <interceptors>    
                                <interceptor name="testInterceptor"   class="com.test.interceptors.TestInterceptor">    
                                </interceptor>    
                        </interceptors>
                        <action name="testAction" class="com.test.action.TestAction"
                                        method="execute">
                                        <interceptor-ref name="testInterceptor"></interceptor-ref>
                                        <result name="success">/Test.jsp&lt;/result>
                                </action>
                        </package>
                <!-- Add packages here -->
        </struts>
        <!--If Multiple interceptors then prepare a Stack -->    
        <struts>
                <package name="default" namespace="/" extends="struts-default" >
               
                        <interceptors>
                                <interceptor name="testInterceptor"   class="com.test.interceptors.TestInterceptor"/>    
                                <interceptor name="testInterceptor1"   class="com.test.interceptors.TestInterceptor1"/>        
                                <interceptor-stack name="basicStack">
                                        <interceptor-ref name="testInterceptor" />
                                        <interceptor-ref name="testInterceptor1" />    
                                </interceptor-stack>
                        </interceptors>
                        <action name="testAction" class="com.test.action.TestAction"
                                        method="execute">
                                        <!-- <interceptor-ref name="basicStack"></interceptor-ref>-->
                                        <result name="success">/Test.jsp/result>
                        </action>
        </package>
                <!-- Add packages here -->
        </struts>
       
2) Write Interceptor Class
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class TestInterceptor implements Interceptor {
        @Override
        public String intercept(ActionInvocation arg0) throws Exception {
                //Write your Specific code here.
                return SUCCESS;
        }      
}

3 comments: