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
  • Selenium with python
    Selenium with Python Training
  • As we know, that Selenium with Python Web Browser Selenium Automation is Gaining Popularity Day by Day. So many Frameworks and Tools Have arisen to get Services to Developers.

  • machine learning with python
    Machine Learning with Python Training
  • Over last few years, Big Data and analysis have come up, with Exponential and modified Direction of Business. That operate Python, emerged with a fast and strong Contender for going with Predictive Analysis.

  • Data science with R
    Data Science With R Training
  • Understanding and using Linear, non-linear regression Models and Classifying techniques for stats analysis. Hypothesis testing sample methods, to get business decisions.

  • data science with python
    Data Science with Python Training
  • Everyone starts Somewhere, first you learn basics of Every Scripting concept. Here you need complete Introduction to Data Science python libraries Concepts.

  • devops with azure
    Devops with Azure Training
  • As we Know Azure DevOps is a Bunch of Services, in guiding Developers. It contains CI/CD, pipelines, code Repositories, Visual Reporting Tools and more code management with version control.

  • python training
    Python Certification Training
  • Python is a dynamic interrupted language which is used in wide varieties of applications. It is very interactive object oriented and high-level programming language.

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

Call Now Button