Upload File With Struts 2 and Spring Security

Struts 2 File Upload Example

In this case you volition learn how to exercise file upload with the help of the congenital-in FileUploadInterceptor . To do this first we demand to get the file course the user. We use the Struts two tags to build our form. The encoding type of the form should be set to multipart/form-data and the HTTP method should be gear up to mail service. The index.jsp page contains the following code.

Create two JSP file in WebRoot folder. index.jsp will display a form to user to upload image. On submit, the file will be uploaded and saved on server. User volition be sent to success.jsp file where File details will be displayed. Copy following lawmaking into it.

index.jsp

<%@ page contentType="text/html; charset=UTF-viii"%> <%@ taglib prefix="due south" uri="/struts-tags"%> <html> <head> <championship>Upload User Prototype</title> </head>   <body> <h2>Struts2 File Upload & Salvage Example</h2> <s:actionerror /> <s:class action="userImage" method="post" enctype="multipart/class-data">     <south:file name="userImage" characterization="User Epitome" size="x"/>     <south:submit value="Upload" align="center" /> </southward:form> </body> </html>                              

At that place are couple of points worth noting in the higher up example. First of all, the form's enctype is set to multipart/class-data. This should be prepare so that file uploads are handled successfully by the file upload interceptor. The next point noting is the form's action method upload and the name of the file upload field – which is userImage. We demand this information to create the action method and the struts configuration.

Next let usa create a simple jsp file success.jsp to display the outcome of our file upload in case information technology becomes success.

success.jsp

<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Success: Upload User Image</championship> </caput> <body>     <h2>Struts2 File Upload Example</h2>     User Paradigm: <s:holding value="userImage"/>     <br/>     Content Type: <s:property value="userImageContentType"/>     <br/>     File Name: <south:belongings value="userImageFileName"/>     <br/>     Uploaded Image:     <br/>     <img src="<south:property value="userImageFileName"/>"/> </body> </html>                            

Following volition be the result file error.jsp in case in that location is some error in uploading the file:

error.jsp

<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>File Upload Error</title> </head> <body> There has been an error in uploading the file. </trunk> </html>                          

Create activity class:

Side by side let us create a Java grade called FileUploadAction.coffee which will take care of uploading file and storing that file at a secure location:

package com.dineshonjava.struts2.action.upload;  import java.io.File;  import javax.servlet.http.HttpServletRequest;  import org.apache.eatables.io.FileUtils; import org.apache.struts2.interceptor.ServletRequestAware;  import com.opensymphony.xwork2.ActionSupport;  /**  * @author Dinesh Rajput  *  */ public class FileUploadAction extends ActionSupport implements ServletRequestAware {  private static final long serialVersionUID = 1L;  private File userImage;  private String userImageContentType;  private Cord userImageFileName;    individual HttpServletRequest servletRequest;    public Cord execute() {   try {       String filePath = servletRequest.getSession().getServletContext().getRealPath("/");       System.out.println("Server path:" + filePath);       File fileToCreate = new File(filePath, this.userImageFileName);          FileUtils.copyFile(this.userImage, fileToCreate);   } catch (Exception e) {       e.printStackTrace();       addActionError(eastward.getMessage());         render INPUT;   }   return SUCCESS;  }    public File getUserImage() {   return userImage;  }    public void setUserImage(File userImage) {   this.userImage = userImage;  }    public Cord getUserImageContentType() {   render userImageContentType;  }    public void setUserImageContentType(String userImageContentType) {   this.userImageContentType = userImageContentType;  }    public String getUserImageFileName() {   return userImageFileName;  }    public void setUserImageFileName(String userImageFileName) {   this.userImageFileName = userImageFileName;  }    @Override  public void setServletRequest(HttpServletRequest servletRequest) {   this.servletRequest = servletRequest;  } }                        

In in a higher place grade file we have declared few attributes:

  • private File userImage; -> This will store actual uploaded File
  • individual String userImageContentType; -> This cord will contain the Content Blazon of uploaded file.
  • private String userImageFileName; -> This string will contain the file name of uploaded file.

The fields userImageContentType and userImageFileName are optional. If setter method of these fields are provided, struts2 will set the information. This is just to get some extra information of uploaded file. Also follow the naming standard if yous providing the content blazon and file proper name string. The name should be ContentType and FileName. For example if the file aspect in activity file is individual File uploadedFile, the content type will be uploadedFileContentType and file name uploadedFileFileName.
Also annotation in higher up action form, we accept implemented interface org.apache.struts2.interceptor.ServletRequestAware . This is to become servletRequest object. We are using this path to save the uploaded file in execute() method. We have used FileUtil.copyFile() method of eatables-io parcel to re-create the uploaded file in root folder. This file will exist retrieved in JSP page and displayed to user.

Configuration files:

Following are the Struts2 configuration properties that control file uploading process:

struts.xml

<?xml version="one.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"     "http://struts.apache.org/dtds/struts-2.0.dtd">   <struts>    <constant name="struts.devMode" value="truthful" />    <parcel proper name="upload" extends="struts-default">       <action proper name="userImage" class="com.dineshonjava.struts2.action.upload.FileUploadAction">       <interceptor-ref name="fileUpload">          <param proper name="maximumSize">2097152</param>          <param name="allowedTypes">              paradigm/png,paradigm/gif,image/jpeg,prototype/pjpeg          </param>        </interceptor-ref>     <interceptor-ref name="defaultStack"></interceptor-ref>     <outcome proper noun="success">success.jsp</result>     <result name="input">alphabetize.jsp</result>      <result name="error">error.jsp</upshot>  </action>    </package>  </struts>                      

Notation that in above entry we have specified 2 parameter to fileUpload interceptor, maximumSize and allowedTypes. These are optional parameters that we tin can specify to interceptor. The maximumSize param will gear up the maximum file size that tin can be uploaded. By default this is 2MB. And the allowedTypes param specify the immune content types of file which can be uploaded. Here we have specified it to be an epitome file (image/png,image/gif,epitome/jpeg,image/pjpeg).

The file upload interceptor also does the validation and adds errors, these error messages are stored in the struts-messsages.properties file. The values of the letters can be overridden by providing the text for the following keys:

  1. struts.messages.mistake.uploading – error when uploading of file fails
  2. struts.letters.error.file.besides.large – error occurs when file size is large
  3. struts.messages.error.content.type.not.allowed – when the content type is not allowed

Following is the content of spider web.xml file:

<?xml version="i.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://world wide web.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="iii.0">   <display-name>Struts2FileUpload</display-name>   <filter>         <filter-proper noun>struts2</filter-proper noun>         <filter-form>             org.apache.struts2.dispatcher.FilterDispatcher         </filter-course>     </filter>     <filter-mapping>         <filter-proper name>struts2</filter-name>         <url-pattern>/*</url-blueprint>     </filter-mapping>     <welcome-file-list>         <welcome-file>index.jsp</welcome-file>     </welcome-file-listing> </web-app>                    

Now Right click on the project proper noun and click Export > War File to create a War file. And so deploy this WAR in the Tomcat's webapps directory. Finally, first Tomcat server and attempt to access
URL http://localhost:8080/doj/index.jsp.
This volition give you post-obit screen:

Struts 2 File Upload Example

Image Upload Screen in case of error-

Struts 2 File Upload Example

Prototype Upload Screen on success-

Struts 2 File Upload Example

Another Epitome Upload Screen on success-

Struts 2 File Upload Example

Download Source Code+Libs
Struts2FileUpload.zip

leewilefored60.blogspot.com

Source: https://www.dineshonjava.com/struts-2-file-upload-example/

0 Response to "Upload File With Struts 2 and Spring Security"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel