Struts 2 custom interceptor with @InterceptorRef example

In previous posts, we learned the hello world applications and setting result path for struts 2 applications. Now, moving ahead in this post, I am giving an example of custom or user defined interceptor configuration using annotations.

An interceptor is a class whose pre-defined method is called each time, a configured server resource is accessed. This can be called before resource access, or after resource access. Please note that resource access here means HTTP request processing also.

Steps summary:
1) Create custom interceptor class which implements com.opensymphony.xwork2.interceptor.Interceptor
2) Implement overridden methods
3) Give definition in struts.xml file
4) Apply on any Action class
Important: Please note that Struts 2 comes with many ready-made interceptor implementations, So make sure you really need to create your own interceptor or something can work for you.

1)& 2) Create custom interceptor class and Implement overridden methods

Below is sample code for custom interceptor and implementation for all overridden methods. Please feel free to add your application logic in appropriate methods.

package com.howtodoinjava.struts2.example.web;

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

public class DemoCustomInterceptor implements Interceptor
{
	private static final long serialVersionUID = 1L;

	@Override
	public void destroy() {
		System.out.println("DemoCustomInterceptor destroy() is called...");
	}

	@Override
	public void init() {
		System.out.println("DemoCustomInterceptor init() is called...");
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception 
	{
		System.out.println("DemoCustomInterceptor intercept() is called...");
		System.out.println(invocation.getAction().getClass().getName());
		return invocation.invoke();
	}
}

3) Give definition in struts.xml file

This is very important step because here you register your interceptor class in struts context and runtime.

<?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>
	<package name="default" namespace="/" extends="struts-default">
		<interceptors>	
			<interceptor name="demoCustomInterceptor" class="com.howtodoinjava.struts2.example.web.DemoCustomInterceptor" />
			<interceptor-stack name="customStack">
	     		<interceptor-ref name="demoCustomInterceptor"/>
				<interceptor-ref name="defaultStack" />
        	</interceptor-stack>
	    </interceptors>	    
	</package>
	
	<constant name="struts.convention.result.path" value="/WEB-INF/jsp/" />
	<constant name="struts.devMode" value="true" />
	<constant name="struts.action.extension" value="action," />
	<constant name="struts.custom.i18n.resources" value="test" />
	<constant name="struts.convention.default.parent.package" value="default"/>
	
</struts>

4) Apply on any Action class

I am applying above interceptor in one such TestAction class.

package com.howtodoinjava.struts2.example.web;

import java.util.Date;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;

@InterceptorRef(value="customStack")
@Results({
	   @Result(name="success", location="success.jsp"),
	   @Result(name="input", location="index.jsp")
})
public class TestAction extends ActionSupport 
{
	private static final long serialVersionUID = 1L;
	
	private String name;
    private Date nowDate;
	
    @Override
    public void validate(){
        if (name==null || name.length()==0)
            addActionError(getText("error.enter.message"));
    }
    @Actions({
        @Action("/"),
        @Action("/test")
    })
    @Override
    public String execute() throws Exception {
        nowDate = new Date();
        return ActionSupport.SUCCESS;
    }
    public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getNowDate() {
        return nowDate;
    }
}

Please note that I have applied the interceptor using @InterceptorRef(value=”customStack”) definition. It can help you in applying multiple interceptors in one go. If you want only specific interceptor only, use its name like this: @InterceptorRef(value=”demoCustomInterceptor”)

Test the application

When I run above application. I observe the server logs in console as follows:

INFO: Loading global messages from [test]

DemoCustomInterceptor init() is called...

//some logs
INFO: Server startup in 1146 ms

DemoCustomInterceptor intercept() is called...
com.howtodoinjava.struts2.example.web.TestAction

Please click below link to download the source code of this project.

Download sourcecode

Happy Learning!!

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial