use of token interceptor in Struts2
The token interceptor in Struts 2 is used to prevent duplicate form submissions and ensure the integrity of transactions that modify data on the server. It helps in mitigating issues such as double form submission by generating and validating unique tokens that are embedded in HTML forms. This mechanism ensures that each form submission is processed only once, thereby preventing unintended duplicate actions and maintaining data consistency.
Table of Contents
Explanation
- 1. Preventing Duplicate Form Submissions:
- Definition: Â Duplicate form submissions can occur when users accidentally or maliciously submit the same form multiple times, leading to unintended actions or data inconsistencies.
- Usage: Â The token interceptor generates a unique token for each form rendered in the web application. This token is submitted with the form and validated on the server side to ensure that the form submission is genuine and not a duplicate.
- 2. Ensuring Data Integrity:
- Definition: Â Data integrity refers to the accuracy, consistency, and validity of data stored and processed by an application.
- Usage: Â By preventing duplicate form submissions, the token interceptor helps maintain data integrity by ensuring that actions that modify data (such as updates or deletions) are performed only once per submission.
Example in Java
Let’s demonstrate the use of token interceptor in a Struts 2 application with a simple example.
java
// pom.xml (Maven dependency for struts2-core)
<!-- Struts 2 Core -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.x.x</version> <!-- Replace with the latest version -->
</dependency>
xml
<!-- struts.xml (Struts 2 configuration) -->
<struts>
<package name="default" extends="struts-default">
<interceptors>
<interceptor name="token" class="org.apache.struts2.interceptor.TokenInterceptor"/>
</interceptors>
<default-interceptor-ref name="token"/>
<action name="submitForm" class="com.example.SubmitFormAction">
<interceptor-ref name="defaultStack"/>
<result name="success">/success.jsp</result>
<result name="input">/form.jsp</result>
</action>
</package>
</struts>
jsp
<!-- form.jsp (JSP page with the form) -->
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form Page</title>
</head>
<body>
<s:form action="submitForm">
<s:textfield label="Name" key="name" />
<s:token name="token"/>
<s:submit value="Submit"/>
</s:form>
</body>
</html>
java
// SubmitFormAction.java (Struts 2 action class)
import com.opensymphony.xwork2.ActionSupport;
public class SubmitFormAction extends ActionSupport {
private String name;
private String token;
public String execute() throws Exception {
// Business logic to process form submission
// Validate token to prevent duplicate submission
if (!validToken()) {
addActionError("Duplicate form submission detected.");
return INPUT; // Redirect back to the form with input errors
}
// Process form data (e.g., save to database)
// Example: Saving 'name' to database
return SUCCESS; // Redirect to success page
}
// Getter and Setter for 'name' and 'token'
// Omitted for brevity
private boolean validToken() {
// Implement logic to validate token
// Typically, compare 'token' received from request with stored token
// Store and retrieve token in session or form
return true; // Dummy implementation for demonstration
}
}
jsp
<!-- success.jsp (JSP page to display success message) -->
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Success Page</title>
</head>
<body>
<h1>Form submitted successfully!</h1>
</body>
</html>
Explanation
- 1. Â Struts Configuration (struts.xml):
- The token interceptor is configured in struts.xml within the <interceptors> section. It is referenced for the submitForm action using <default-interceptor-ref> to ensure that this interceptor is applied by default to this action.
- The submitForm action configuration includes the defaultStack interceptor stack, which typically includes interceptors for validation, conversion, and other common tasks.
- 2. Â Form JSP (form.jsp):
- The form is created using Struts tags (<s:form>, <s:textfield>, <s:token>, <s:submit>).
- <s:token> tag generates a hidden field with a unique token that is submitted with the form.
- 3. Â Action Class (SubmitFormAction.java):
- SubmitFormAction class handles the form submission logic.
- It includes a method validToken() to validate the token received with the form submission.
- If the token is valid, the action processes the form data (here, a dummy example of saving ‘name’ to a database) and returns SUCCESS to redirect to success.jsp.
- If the token is not valid (indicating a duplicate submission), it adds an action error and returns INPUT to redirect back to form.jsp with error messages.
- 4. Â User Experience:
- When a user submits the form (form.jsp), the token interceptor ensures that the form submission is validated against duplicate submissions.
- If the form submission is genuine (i.e., token is valid), the action processes the form data and redirects to success.jsp.
- If the form submission is a duplicate (i.e., token is invalid), the user is redirected back to form.jsp with an error message.
Conclusion
The token interceptor in Struts 2 enhances application security and maintains data integrity by preventing duplicate form submissions. It generates and validates unique tokens for each form submission, ensuring that actions modifying data are executed only once per submission. This mechanism is essential for handling transactional operations and maintaining a reliable user experience in web applications built with Struts 2.