Interceptor

Interceptor

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()

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.

MyInterceptor.java

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”);

stack.set(“name”,s.toUpperCase());

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 .

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=”abc” extends=”struts-default”>

<interceptors>

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

</interceptors>

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

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

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

<result>welcome.jsp</result>

</action>

</package>

</struts>

 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
   Parameter
ordered
paramNameMaxLength
excludeParams
acceptParamNames

 

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

Parameter
delay
delaySleepInterval
threadPriority

 

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) {

this.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

Parameter
logEnabled
logLevel
logCategory

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.

index.jsp

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

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

<html>

<head>

<title>Upload User Image</title>

</head>

<body>

<h2>

Struts2 File Upload & Save Example without Database

</h2>

<s:actionerror />

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

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

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

</s:form>

</body>

</html>

2) Create SuccessUserImage.jsp

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

SuccessUserImage.jsp

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

uri=”/struts-tags”%>

<html>

<head>

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

</head>

<body>

<h2>

Struts2 File Upload Example

</h2>

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″ />

</body>

</html>

3) Create the action class

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

 RegisterAction.java

package com.javaspot;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;

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.
 struts.xml

<!DOCTYPE struts PUBLIC

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

“http://struts.apache.org/dtds/struts-2.0.dtd”>

 

<struts>

<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”>

image/png,image/gif,image/jpeg,image/pjpeg

</param>

</interceptor-ref>

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

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

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

</action>

</package>

        </struts>

Drop Us A Query

Trending Courses
  • Python and Django Online 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.

  • Tableau Online Training
  • Tableau is a Software company that caters interactive data visualization products that provide Business Intelligence services. The company’s Head Quarters is in Seattle, USA.

  • MicroStrategy Online Training
  • Micro Strategy is one of the few independent and publicly trading Business Intelligence software provider in the market. The firm is operational in 27 Countries around the globe.

  • PEGA (PRPC) 7.2 Certification Online Training
  • Pega Systems Inc. is a Cambridge, Massachusetts based Software Company. It is known for developing software for Customer Relationship Management (CRM) and Business process Management (BPM).

  • Workday Online Training
  • Workday specialises in providing Human Capital Management, Financial Management and payroll in online domain.It is a major web based ERP software vendor.

  • Power BI Online Training
  • Power BI is business analytics service by Microsoft. With Power BI, end users can develop reports and dashboards without depending on IT staff or Database Administrator.


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