Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Struts2: Token interceptor

Some times user may submit the Request twice, (or) refresh the page, in those conditions we shouldn’t let the application behave in strange way. By using Token interceptor, we can get rid of these double click kinds of problems. Whenever struts2 find double submission, token interceptor returns the result invalid.token, which can be mapped in your action configuration.

How to set a token in your form?
Use the tag <s:token/> in your form. This tag is required and must be used in the forms that submit to actions protected by this interceptor. Any request that does not provide a token (using the token tag) will be processed as a request with an invalid token.

In brief, following are the action, jsp files I am going to use.

File
Description
EntryAction.java
Action class that process the form.
index.jsp
Simple Html form
invalid_token.jsp
Request redirect to this page on double submissions
success.jsp
You will get the page, after successful submission of the form (input.jsp).

Following step-by-step procedure explains simple application that uses token interceptor.

Step 1: Create new dynamic web project ‘struts2_token’ in Eclipse.

File -> New -> Dynamic Web Project.

Step 2: Mavenize the project. Right click the project -> Properties -> Configure -> Convert To Maven Project.


Open pom.xml, update struts2 maven dependencies. I am going to use following maven dependency.

<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.20</version>
</dependency>

Step 3: Define index.jsp like below. 

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Insert title here</title>
</head>

<body>
<s:form action="addEntry">
<s:textfield label="Name" name="name" />
<s:textfield label="Address" name="address" />
<s:submit value="ADD" />
<s:token />
</s:form>
</body>

</html>


Step 4: Define success.jsp like below.

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Your details are submitted successfully</h1>
</body>
</html>


Define invalid_token.jsp like below. 
invalid_token.jsp


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Struts2: Token interceptor

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×