Searching...
Friday, 4 October 2013

How to implement Interceptors in Struts 2 ?

20:26

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 (HelloNameInterceptor.java)

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;
    @Override
    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;
    }
    @Override
    public void destroy() {
        System.out.println("Filter destroying");
    }
    @Override
    public void init() {
        System.out.println("Filter initializing");
    }
}

3. Configuring Interceptor in Struts.xml

<?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>
    <include file="struts-default.xml"/>
    <package name="com" extends="struts-default">
    <interceptors>
    <interceptor name="namefilter" class="com.pretech.HelloNameInterceptor">
    </interceptor>
  </interceptors>
        <action name="helloaction" class="com.pretech.HelloWorldAction">
              <interceptor-ref name="namefilter" />
        <interceptor-ref name="defaultStack" />
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>

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

0 comments: