Back to: Java Struts Tutorials
Struts 2 Interceptors with Examples
In this article, I am going to discuss Struts 2 Interceptors with Examples. Please read our previous article where we discussed Struts 2 ActionSupport.
What are Interceptors in Struts 2?
In Struts 2, interceptors are components that allow you to intercept and customize the behavior of the framework’s processing flow. They provide a way to modify or enhance the execution of an action before and after it is invoked.
Interceptors are configured in the struts.xml configuration file and are applied globally or on a per-action basis. Each interceptor is associated with an interceptor stack, which is a sequential list of interceptors that are executed in a specific order.
Here are some key points about interceptors in Struts 2:
- Pre-Processing and Post-Processing: Interceptors can perform actions before and after the execution of an action. They can intercept request, modify parameters, perform validation, handle security checks, and more. This allows you to add cross-cutting concerns to your application’s actions.
- Customization and Extension: Interceptors provide a way to customize and extend the behavior of the framework without modifying the core code. By adding or removing interceptors in the interceptor stack, you can change the processing flow and introduce additional functionality.
- Chaining: Multiple interceptors can be configured in an interceptor stack, and they are executed in the order defined. Each interceptor has the ability to invoke the next interceptor in the stack or skip further processing, allowing for fine-grained control over the flow.
- Predefined Interceptors: Struts 2 provides a set of predefined interceptors that address common requirements, such as validation, logging, exception handling, file uploading, and more. These interceptors can be easily configured and utilized in your application.
- Custom Interceptors: You can create your own custom interceptors by implementing the Interceptor interface. This gives you the flexibility to implement specific behavior and integrate it into the framework.
By leveraging interceptors, you can modularize and enhance the behavior of your actions, making your application more flexible, reusable, and easier to maintain. Interceptors provide a powerful mechanism for adding cross-cutting concerns and customizing the request processing flow in Struts 2.
List of Interceptors in Struts2
Struts 2 provides several built-in interceptors that can be used to customize the behavior of the framework. Here is a list of commonly used interceptors in Struts 2:
- params: This interceptor sets the parameters received in the HTTP request onto the action class. It handles parameter parsing and type conversion.
- workflow: This interceptor controls the workflow and state transitions in your application. It provides support for conditional processing, branching, and decision-making based on the state of the action.
- validation: This interceptor performs validation of user input based on validation rules defined in the action class or in external XML files. It handles the validation process and adds field errors and error messages.
- exception: This interceptor handles exceptions that occur during the execution of an action. It allows you to define custom exception-handling logic, such as mapping specific exceptions to result pages or performing cleanup tasks.
- fileUpload: This interceptor handles file uploads. It allows you to receive file data from a multipart HTTP request and store the uploaded files in a temporary location or process them as needed.
- logging: This interceptor provides logging capabilities. It can log information about the execution of actions, including input parameters, return values, and any errors or exceptions that occur.
- paramsPrepareParamsStack: This is a predefined interceptor stack that includes the params interceptor and prepares the parameters for the next action execution. It is often used when dealing with chained actions or actions that need to pass parameters to subsequent actions.
- servletConfig: This interceptor provides access to the ServletConfig object and allows you to retrieve servlet context parameters or perform initialization tasks based on the servlet configuration.
- scopedModelDriven: This interceptor integrates with the XWork framework’s model-driven feature and handles scoping of model objects. It allows you to manage model objects with different scopes, such as request scope, session scope, or application scope.
These are just a few examples of interceptors available in Struts 2. The framework provides more interceptors that cater to various needs, and you can also create your own custom interceptors to meet specific requirements.
Implementing Interceptors in Struts 2
For this project, we will be using the same project from the previous article (Struts2 ActionSupport). 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"> <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>
To implement interceptors, only the struts.xml file needs to be modified.
Step 1: Modify struts.xml as follows:
We have added two extra lines which act as interceptors.
Step 2: Compile and execute the program on the Tomcat server. The following page must open in your default web browser:
Enter any name and click on the submit button. The following text must be printed in the terminal:
INFO: Server startup in 1135 ms
13/07/2023 10:40:53 AM
com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
INFO: Executed action [//HelloAction!execute] took 53 ms.
Congratulations! You have successfully completed an application using interceptors in struts2.
The complete 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> <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>
In the next article, I am going to discuss Struts 2 Custom Interceptors. Here, in this article, I try to explain Struts 2 Interceptors with Examples and I hope you enjoy this Struts 2 Interceptors article.
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.