Click to rate this post!
[Total: 0 Average: 0]


Struts 2 Custom Interceptor

In struts 2, we can make the custom interceptor by actualizing the Interceptor interface in a class and abrogating its three life cycle technique.For making the custom Interceptor interface must be executed. It has three strategies:

public void init()It is summoned just once and used to introduce it

public String intercept(ActionInvocation ai) It is summoned at each demand, it is utilized to characterize the demand handling rationale. On the off chance that it returns string, result page will be summoned, in the event that it returns conjure() technique for ActionInvocation interface, next interceptor or activity will be summoned.

public void destroy()

JAVA Tutorial Video

Case to make custom interceptor :

In this illustration, we will make custom that believers ask for preparing information into capitalized letter.

You have to take after 2 stages

1) Create an interceptor

By this interceptor, we are changing over the name property of activity class into capitalized letter.

The getStack() technique for ActionInvocation restores the reference of ValueStack.

We are getting the esteem set in the name property by find String technique for ValueStack. The set technique for ValueStack sets the name property by the predefined esteem. In such case, we are changing over the estimation of name property into capitalized letter and putting away it into the valuestack.

package com;

import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.interceptor.Interceptor;

import com.opensymphony.xwork2.util.ValueStack;

public class MyInterceptor implements Interceptor{

public void init() {}

public String intercept(ActionInvocation ai) throws Exception {

ValueStack stack=ai.getStack();

String s=stack.findString(“name”);


return ai.invoke();


public void destroy() {}


2) Define the entry  in the struts.xml file

To characterize the interceptor, we have to pronounce an interceptor first. The component of bundle is utilized to determine interceptors. The component of interceptors is utilized to characterize the custom interceptor. Here, we are characterizing the custom .

The interceptor-ref subelement of activity determines the  that will be connected for this activity. Here, we are determining the defaultstack interceptors .


<?xml version=”1.0″ encoding=”UTF-8″ ?>

<!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts

Configuration 2.1//EN” “”>


<package name=”abc” extends=”struts-default”>


<interceptor name=”upper” class=”com.MyInterceptor”></interceptor>


<action name=”login” class=”com.Login”>

<interceptor-ref name=”defaultStack”></interceptor-ref>

<interceptor-ref name=”upper”></interceptor-ref>





 Struts 2 params interceptor

  The params interceptor otherwise called parameters interceptor is utilized to set all parameters on the valuestack. It is found in the default stack bydefault. So you don’t have to indicate it explicitely.

Inner working of params interceptor

It gets all parameters by calling the getParameters() strategy for ActionContext and sets it on the valuestack by calling the setValue() technique for ValueStack.

 Parameters of params interceptor


Struts 2 execAndWait interceptor 

The execAndWait interceptor otherwise called execute and hold up interceptor is utilized to show the middle of the road result.

It is prescribed to use for long running activity.

It is not found in the default stack by default. So you have to determine it explicitly.

On the off chance that you don’t determine “hold up” result, struts system shows a middle outcome until the point when your demand is finished.

For the custom middle of the road result, you have to characterize “hold up” result in struts.xml document. In your page, you can show handling picture and so forth. In this way, it is smarter to determine the custom outcome.

Parameters of execAndWait interceptor



prepare interceptor

The get ready interceptor calls prepre() strategy on the activity in the event that it executes Preparable interface. It calls get ready() technique before the execute() strategy.

 Parameters of prepare interceptor


Parameter Description
alwaysInvokePrepare It is set to true bydefault.

 Prepare interceptor

Action class

package com.javaspot;

import com.opensymphony.xwork2.Preparable;

public class LoginAction implements Preparable{

private String name,password;

public String getName() {

return name;


public void setName(String name) { = name;


public String getPassword() {

return password;


public void setPassword(String password) {

this.password = password;


public void prepare() throws Exception {

System.out.println(“preparation logic”);


public String execute(){

System.out.println(“actual logic”);

return “success”;



modelDriven interceptor 

The modelDriven interceptor makes other model question as the default protest of valuestack.

To utilize the modelDriven interceptor, you have to actualize ModelDriven interface in your activity class and abrogate its strategy getModel(). It is found in the default stack by-default. So you don’t have to determine it explicitly. In our web application, there might happen special case anytime.

Exception Handling -- exception interceptor

To defeat this issue, struts 2 gives an instrument of worldwide special case taking care of where we can show a worldwide outcome to the client.

Struts 2 consequently log the uncaught exemptions and sidetracks the client to the blunder handler page.

Understanding the inside working of special case interceptor

On the off chance that there happens special case, it is wrapped in ExceptionHolder and pushed in the valuestack with the goal that we can without much of a stretch get to exemption question from the outcome.

Parameters of exception interceptor


File Upload

The fileUpload interceptor naturally works for every one of the solicitations that incorporates documents. We can utilize this interceptor to control the working of document transfer in struts2, for example, characterizing permitted sorts, most extreme record estimate.

Parameters of fileupload interceptor

Parameter Description
maximumSize specifies maximum size of the file to be uploaded.
allowedTypes specifies allowed types. It may be image/png, image/jpg etc.

Automatically added parameters

  1. String fileName represents the filename of the file.
  2. String contentType specifies the content type of the file.
1) Create UserImage.jsp

This jsp page creates a form using struts UI tags. It receives file from the user.


<%@ page contentType=”text/html; charset=UTF-8″%>

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



<title>Upload User Image</title>




Struts2 File Upload & Save Example without Database


<s:actionerror />

<s:form action=”userImage” method=”post” enctype=”multipart/form-data”>

<s:file name=”userImage” label=”Image” />

<s:submit value=”Upload” align=”center” />




2) Create SuccessUserImage.jsp

This jsp page creates a form using struts UI tags. It receives name, password and email id from the user.


<%@ page contentType=”text/html; charset=UTF-8″%><%@ taglib prefix=”s”




<title>Success: Upload User Image</title>




Struts2 File Upload Example


User Image: <s:property value=”userImage” /><br/>

Content Type:<s:property value=”userImageContentType” /><br/>

File Name:  <s:property value=”userImageFileName” /><br/>

Uploaded Image: <img src=”userimages/<s:property value=”userImageFileName”/>”

width=”100″ height=”100″ />



3) Create the action class

 This action class inherits the ActionSupport class and overrides the execute method.

package com.javaspot;


import javax.servlet.http.HttpServletRequest;


import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport{

private File userImage;

private String userImageContentType;

private String userImageFileName;

public String execute() {

try {

String filePath = ServletActionContext.getServletContext().getRealPath(“/”).concat(“userimages”);

System.out.println(“Image Location:” + filePath);//see the server console for actual location

File fileToCreate = new File(filePath,userImageFileName);

FileUtils.copyFile(userImage, fileToCreate);//copying source file to new file

return SUCCESS;


public File getUserImage() {

return userImage;


public void setUserImage(File userImage) {

this.userImage = userImage;


public String getUserImageContentType() {

return userImageContentType;


  public void setUserImageContentType(String userImageContentType) {

this.userImageContentType = userImageContentType;


public String getUserImageFileName() {

return userImageFileName;


public void setUserImageFileName(String userImageFileName) {

this.userImageFileName = userImageFileName;



4) Create struts.xml
This xml file defines an extra result by the name input, and an interceptor jsonValidatorWorkflowStack.


“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”




<package name=”fileUploadPackage” extends=”struts-default”>

<action name=”userImage” class=”com.javaspot.FileUploadAction”>

<interceptor-ref name=”fileUpload”>

<param name=”maximumSize”>2097152</param>

<param name=”allowedTypes”>




<interceptor-ref name=”defaultStack”></interceptor-ref>

<result name=”success”>SuccessUserImage.jsp</result>

<result name=”input”>UserImage.jsp</result>




to our newsletter

Drop Us A Query

Trending Courses
  • Microsoft Azure Architect Technologies(AZ-300) | ITGuru
    Microsoft Azure Architect Technologies(AZ-300)
  • Azure is a great Microsoft Cloud Computing platform in providing various cloud services through online. ITGuru Certified Azure Architect certification course gives you the practical knowledge on Azure Cloud platform through real-world use cases from live experts

  • ServiceNow Admin Training | ITGuru
    ServiceNow Admin Training
  • Getting knowledge of cloud platforms like ServiceNow is essential in today’s world for the smooth running of projects in cloud platform. Turn your dream to the reality of becoming the Certified ServiceNow Administrator through ServiceNow Administration online certification Course with practical examples by live industry experts through online at ITGuru with real-world use cases.

  • Workday Financials Training | ITGuru
    Workday Financials Training
  • knowing the basics on any platform like Workday is not enough to sustain the IT industry. Hence it is essential to go beyond on Workday basics like Workday Financials training which lets you know the application of Financials management in real -world use cases from ITGuru Live Experts in a practical way.

  • Workday Training
  • An organization is considered as the best one when it offers the best benefits to the employee. Moreover, the greater the employee benefits, the greater the contribution to the organization. ITGuru let you know the practical workday Human Resource Management(HRM) features with live examples by experts

  • Python Online Course | ITGuru
    Python Online Course
  • Turn your dream into reality by ITGuru live experts with real-world use cases through practical knowledge on python online course and become the certified associate in python programming and become a master in python programming

  • Python Programming | ITGuru
    Python Programming
  • Python is the trending programming language in the IT industry. Mastering in python programming gives you more value among the people in the IT industry. Hence start today to learn python programming online by live experts with real-time uses cases at ITGuru

100% Secure Payments. All major credit & debit cards accepted.

Call Now Button