Friday, 4 October 2013

How to implement Interceptors in Struts 2 ?


In this example we will see how to implement Interceptors. Struts 2 Framework API provides mechanism to controlling requests using interceptors.

1. Create a struts web application

Please see previous examples to create simple Struts 2 web application

2. Create an Interceptor class (

To create interceptors we have to implement Interceptor interface and override intercept method. Inside this method we can do the intercepting whatever needed. In this example i am adding logging before and after executing action.

package com.pretech;

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

public class HelloNameInterceptor implements Interceptor {
    private static final long serialVersionUID = 1L;
    public String intercept(ActionInvocation invoke) throws Exception {
        String result;
        System.out.println("Before calling action" + invoke.getAction().getClass());
        result = invoke.invoke();
        System.out.println("After calling action");
        return result;
    public void destroy() {
        System.out.println("Filter destroying");
    public void init() {
        System.out.println("Filter initializing");

3. Configuring Interceptor in Struts.xml

<?xml version="1.0" encoding="UTF-8"?>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    <include file="struts-default.xml"/>
    <package name="com" extends="struts-default">
    <interceptor name="namefilter" class="com.pretech.HelloNameInterceptor">
        <action name="helloaction" class="com.pretech.HelloWorldAction">
              <interceptor-ref name="namefilter" />
        <interceptor-ref name="defaultStack" />
            <result name="success">/success.jsp</result>

4. Run application

Run this application and input your name as parameter, in the console log we will see below intercepting details

Filter initializing
Before calling actionclass com.pretech.HelloWorldAction
After calling action