Interceptors in Struts 2: See all request parameters before action

Interceptor is a class without state that works like a filter. These are objects that dynamically intercept your defined action invocations. They give the advantage to developer, just define any code which can be executed before the action or after the action.
Using interceptor you can prevent the execution of an action. So over all you can say that interceptors provide the interface where you can encapsulate common functionality in a re-usable form for more than one action.
Signature: public interface Interceptor extends Serializable


See an example for checking the values in request parameters invoked from a jsp page before going to action:::
*************************************************************

package com.example.web.interceptor;


import java.util.Iterator;
import java.util.Map;




import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class TestActionInterceptor implements Interceptor {

/**

*/
private static final long serialVersionUID = 1L;


public void destroy() {
System.out.println("CustomInterceptor destroy() is called...");

}


public void init() {
System.out.println("CustomInterceptor init() is called...");

}


public String intercept(ActionInvocation actionInvocation) throws Exception {
    System.out.println("CustomInterceptor, before invocation.invoke()...");

    Map params = actionInvocation.getInvocationContext().getParameters();
// Getting all request parameters from jsp page on which you have called any
// action
    System.out.println(params.size());
    Iterator itr = params.entrySet().iterator();
while(itr.hasNext()) {
   Object element = itr.next(); 
   System.out.print(element + " ");
   Map.Entry pairs = (Map.Entry)itr.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());

System.out.println("Stack :"+actionInvocation.getStack().size());
System.out.println("Stack :"+actionInvocation.getStack().VALUE_STACK);
params =  actionInvocation.getStack().getContext();
itr = params.entrySet().iterator();
while(itr.hasNext()) {
   Object element = itr.next(); 
   System.out.print(" --> "+element + " ");
   Map.Entry pairs = (Map.Entry)itr.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}

System.out.println(" Action Name  : "+actionInvocation.getAction().toString());
String result = actionInvocation.invoke();
System.out.println(" Result : "+ result);

System.out.println("CustomInterceptor, after invocation.invoke()...");

return result;
}


}


************************************************************


Comments

Post a Comment

Popular posts from this blog

Read Images from a xlsx file using Apache POI

Read Excel using Apache POI - Exception in thread "main" org.apache.poi.poifs.filesystem.OfficeXmlFileException:

Struts 2 : Warning :No configuration found for the specified action: 'Login.action' in namespace: '/'