HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

Struts 2 custom interceptor with @InterceptorRef example

By Lokesh Gupta | Filed Under: Struts 2

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!!

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Feedback, Discussion and Comments

  1. Sonal Agwani

    April 7, 2016

    Is it possible to create interceptor using ONLY annotation(without XML)

    Reply
    • Lokesh Gupta

      April 7, 2016

      I guess.. no.

      Reply

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

Struts 2 Tutorial

  • Struts 2 – Hello World Example
  • Struts 2 – Annotations Example
  • Struts 2 – @InterceptorRef
  • Struts 2 – Set Result Path
  • Spring + Struts 2 + Hibernate
  • Unable to find interceptor class
  • Unable to find a result type

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap