Struts 2 Custom Interceptors

Struts 2 Custom Interceptors with Examples

In this article, I am going to discuss Struts 2 Custom Interceptors with Examples. Please read our previous article where we discussed Struts 2 Interceptors.

What are Custom Interceptors in Struts 2?

Custom interceptors in Struts 2 are interceptors that you can create to implement custom behavior and add additional processing logic to the framework’s execution flow. By creating custom interceptors, you can extend the capabilities of Struts 2 and tailor the behavior of your application to meet specific requirements.

Steps to Create Custom Interceptor in Struts 2

To create a custom interceptor in Struts 2, you need to follow these steps:

  1. Implement the Interceptor interface: Create a Java class that implements the Interceptor interface. This interface defines methods that allow you to intercept and customize the request processing flow.
  2. Implement the interceptor methods: The Interceptor interface has several methods that you can implement, such as init(), destroy(), and intercept(). The intercept() method is the most important one, as it contains the interceptor’s logic and is invoked during the request processing.
  3. Define interceptor configuration: In the struts.xml configuration file, define a new interceptor element that references your custom interceptor class. You can specify the name, class, and any additional parameters required by your interceptor.
  4. Include the interceptor in the interceptor stack: Once your custom interceptor is defined, you can include it in the interceptor stack. By configuring the stack in the struts.xml file, you can specify the order in which the interceptors are executed.
  5. Apply the interceptor stack to actions: Finally, you can apply the interceptor stack to specific actions in the struts.xml file. This determines which actions will be intercepted and have the custom interceptor’s logic applied.

By creating custom interceptors, you have the flexibility to implement specialized functionality, such as custom logging, auditing, caching, security checks, or any other processing that is specific to your application’s needs. Custom interceptors allow you to encapsulate and reuse common behavior across multiple actions, making your application more modular and easier to maintain.

Implementing Interceptors in Struts 2

For this project, we will be using the same project from the previous article (Struts2 Interceptors). It should contain the following files:

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.dotnet</groupId>
  <artifactId>strutex</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <dependencies>
   <dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-core</artifactId>
    <version>6.1.2.1</version>
   </dependency>
   
   <dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-convention-plugin</artifactId>
    <version>6.1.2.1</version>
   </dependency>
   
   <dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts-taglib</artifactId>
    <version>1.3.10</version>
   </dependency>
   
   <dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.0.0</version>
   </dependency>
  </dependencies>
  
  <build>
   <plugins>
    <plugin>
     <groupId>org.apache.maven.plugins</groupId>
    	  <artifactId>maven-compiler-plugin</artifactId>
    	  <version>3.11.0</version>
    	  <configuration>
     <source>17</source>
     <target>17</target>
    </configuration>
    </plugin>
   </plugins>
  </build>
</project>
src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemalocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/web-app_3_0.xsd"
id="apache-struts-config-example"
version="3.0">

 <display-name>Struts Config XML</display-name>
 
 <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>
 
 <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

</web-app>
src/main/webapp/index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Example of Struts</title>
 </head>
 
 <body>
  <form action="hello.action">
   <p>What is your name?</p>
   <input type="text" name="userName"/>
   <input type="submit" value="submit"/>
  </form>
 </body>
</html>
src/main/java/com/dotnet/HelloAction.java
package com.dotnet;

import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ActionSupport;

@Action("/hello")
public class HelloAction extends ActionSupport
{
 public String execute()
 {
  if(userName.equalsIgnoreCase("world"))
   return SUCCESS;
  else
   return ERROR;
 }
 
 private String userName;

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }
}
src/main/webapp/results.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>

 <head>
  <title>Results page</title>
 </head>

 <body>
  <p>Hello <s:property value="userName"/>!</p>
 </body>
</html>
src/main/resources/struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>
 <package name="default" extends="struts-default">
  <action name="hello" class="com.dotnet.HelloAction" method="execute">
   <interceptor-ref name="params"/>
   <interceptor-ref name="timer"/>
   <result name="success">/results.jsp</result>
   <result name="error">/error.jsp</result>
  </action>
 </package>
</struts>
src/main/webapp/error.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>

<html>  
   <head>
      <title>Access Denied</title>
   </head>
   
   <body>
      You are not authorized to view this page.
   </body>
</html>

Step 1: Create a new file called Interceptor.java in the src/main/java directory. Remember to put it in the same package as HelloAction.java. Add the following content to the file:

Struts 2 Custom Interceptors with Examples

This interface contains function definitions that will later be implemented by other concrete classes.

Step 2: Create a new file called MyCustomInterceptor.java in the src/main/java directory. Remember to put it in the same package as HelloAction.java and Interceptor.java. Add the following content to the file:

Struts 2 Custom Interceptors with Examples

Step 3: Modify struts.xml as follows:

Struts 2 Custom Interceptors with Examples

We have made two modifications:

  1. Defined the interceptor (on lines 9-11)
  2. Implemented the interceptor (on line 15)

Step 4: Compile and execute the program on the Tomcat server. The following page must open in your default web browser:

Struts 2 Custom Interceptors with Examples

Enter any name and click on the submit button. The following text must be printed in the terminal:

Struts 2 Custom Interceptors with Examples

Congratulations! You have successfully completed an application using custom interceptors in struts2.

The Complete Example Code
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.dotnet</groupId>
  <artifactId>strutex</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <dependencies>
   <dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-core</artifactId>
    <version>6.1.2.1</version>
   </dependency>
   
   <dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-convention-plugin</artifactId>
    <version>6.1.2.1</version>
   </dependency>
   
   <dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts-taglib</artifactId>
    <version>1.3.10</version>
   </dependency>
   
   <dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.0.0</version>
   </dependency>
  </dependencies>
  
  <build>
   <plugins>
    <plugin>
     <groupId>org.apache.maven.plugins</groupId>
    	  <artifactId>maven-compiler-plugin</artifactId>
    	  <version>3.11.0</version>
    	  <configuration>
     <source>17</source>
     <target>17</target>
    </configuration>
    </plugin>
   </plugins>
  </build>
</project>
src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemalocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/web-app_3_0.xsd"
id="apache-struts-config-example"
version="3.0">

 <display-name>Struts Config XML</display-name>
 
 <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>
 
 <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

</web-app>
src/main/webapp/index.html
<!DOCTYPE html>
<html>
 <head>
  <title>Example of Struts</title>
 </head>
 
 <body>
  <form action="hello.action">
   <p>What is your name?</p>
   <input type="text" name="userName"/>
   <input type="submit" value="submit"/>
  </form>
 </body>
</html>
src/main/java/com/dotnet/HelloAction.java
package com.dotnet;

import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ActionSupport;

@Action("/hello")
public class HelloAction extends ActionSupport
{
 public String execute()
 {
  if(userName.equalsIgnoreCase("world"))
   return SUCCESS;
  else
   return ERROR;
 }
 
 private String userName;

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }
}
src/main/webapp/results.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>

 <head>
  <title>Results page</title>
 </head>

 <body>
  <p>Hello <s:property value="userName"/>!</p>
 </body>
</html>
src/main/resources/struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>
 <constant name="struts.devmode" value="true"/>
 
 <package name="default" extends="struts-default">
  <interceptors>
   <interceptor name="mycustominterceptor" class="com.dotnet.MyCustomInterceptor"/>
  </interceptors>
  
  <action name="hello" class="com.dotnet.HelloAction" method="execute">
   <interceptor-ref name="params"/>
   <interceptor-ref name="mycustominterceptor"/>
   <result name="success">/results.jsp</result>
   <result name="error">/error.jsp</result>
  </action>
 </package>
</struts>
src/main/webapp/error.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>

<html>  
   <head>
      <title>Access Denied</title>
   </head>
   
   <body>
      You are not authorized to view this page.
   </body>
</html>
src/main/java/com/dotnet/Interceptor.java
package com.dotnet;

import java.io.Serializable;

import com.opensymphony.xwork2.ActionInvocation;

public interface Interceptor extends Serializable
{
 void destroy();
 void init();
 String intercept (ActionInvocation invocation) throws Exception;
}
src/main/java/com/dotnet/MyCustomInterceptor.java
package com.dotnet;

import com.opensymphony.xwork2.ActionInvocation;

public class MyCustomInterceptor implements Interceptor
{

 @Override
 public void destroy()
 {
  System.out.print("Destroying MyCustomInterceptor");
 }

 @Override
 public void init()
 {
  System.out.print("Intialising MyCustomInterceptor");
 }

 @Override
 public String intercept(ActionInvocation invocation) throws Exception
 {
  System.out.print("Processing before action invocation.");
  String result = invocation.invoke();
  System.out.print("Processing after action invocation.");
  return result;
 }
}

In the next article, I am going to discuss Struts 2 Results Types with Examples. Here, in this article, I try to explain Struts 2 Custom Interceptors with Examples and I hope you enjoy this Struts 2 Custom Interceptors article.

Leave a Reply

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