Log In to start Learning

Login via

Post By Admin Last Updated At 2020-06-15
InterceptorStruts 2 Custom InterceptorIn 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

[embed]https://www.youtube.com/watch?v=Mb8nG-NH6gg&t=2835s[/embed]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 stages1) Create an interceptorBy 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.javapackage 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<package name="abc" extends="struts-default">class="com.MyInterceptor">class="com.Login">welcome.jsppackage> 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 interceptorThe 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
alwaysInvokePrepareIt 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 interceptorTo 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

maximumSizespecifies maximum size of the file to be uploaded.
allowedTypesspecifies 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 Imagetitle>head><body><h2>Struts2 File Upload & Save Example without Databaseh2><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 Imagetitle>head><body><h2>Struts2 File Upload Exampleh2>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.javapackage 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 locationFile fileToCreate = new File(filePath,userImageFileName);FileUtils.copyFile(userImage, fileToCreate);//copying source file to new filereturn 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><package name="fileUploadPackage" extends="struts-default"><action name="userImage" class="com.javaspot.FileUploadAction"><interceptor-ref name="fileUpload"><param name="maximumSize">2097152param><param name="allowedTypes">image/png,image/gif,image/jpeg,image/pjpegparam>interceptor-ref><interceptor-ref name="defaultStack">interceptor-ref><result name="success">SuccessUserImage.jspresult><result name="input">UserImage.jspresult>action>package>        struts>