IT Certificaions

Google Cloud Platform

Wednesday, October 5, 2011

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
    Iterator itr = params.entrySet().iterator();
while(itr.hasNext()) {
   Object element =; 
   System.out.print(element + " ");
   Map.Entry pairs = (Map.Entry);
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 =; 
   System.out.print(" --> "+element + " ");
   Map.Entry pairs = (Map.Entry);
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;