struts2登录注册示例_Struts 2文件上传示例

struts2登录注册示例

Welcome to Struts 2 file upload example. File Upload is one of the common tasks of a web application and Struts 2 provides built-in feature for single and multiple file upload through FileUploadInterceptor.

欢迎使用Struts 2文件上传示例。 文件上传是Web应用程序的常见任务之一,Struts 2为通过FileUploadInterceptor上传单个和多个文件提供了内置功能。

Struts 2文件上传 (Struts 2 File Upload)

Struts 2 FileUploadInterceptor interceptor is configured in the struts-default package that we usually extend in Struts 2 package configuration.

Struts 2 FileUploadInterceptor拦截器是在struts-default软件包中配置的,我们通常在Struts 2软件包配置中对其进行扩展。

FileUploadInterceptor also provide options to set the maximum file size limit, allowed file types and extensions that can be uploaded to the server.

FileUploadInterceptor还提供用于设置最大文件大小限制,允许的文件类型以及可以上传到服务器的扩展名的选项。

Struts 2 provide option to configure the maximum file size limit through struts.multipart.maxSize variable. This comes handy to set the limit to upload files incase of multiple files uploading in a single request.

Struts 2提供了通过struts.multipart.maxSize变量配置最大文件大小限制的选项。 如果在单个请求中上传多个文件,则可以方便地设置上传文件的限制。

FileUploadInterceptor intercepts the request with enctype as “multipart/form-data” and automatically saves the file in the temp directory and provide useful reference to File, file name and file content type to action classes to save the file at specified location.

FileUploadInterceptor截获enctype为“ multipart / form-data”的请求,并自动将文件保存在temp目录中,并为操作类提供对File,文件名和文件内容类型的有用引用,以将文件保存在指定位置。

Struts 2文件上传示例 (Struts 2 File Upload Example)

We will look into the implementation through a sample Struts 2 project where we will upload single file as well as multiple files to server. Our final project structure looks like below image.

我们将通过一个示例Struts 2项目来研究实现,在该项目中我们将单个文件以及多个文件上传到服务器。 我们的最终项目结构如下图所示。

Struts 2文件上传配置 (Struts 2 File Upload Configuration)

Let’s look at different parts of the application for uploading a single file.

让我们看一下应用程序中用于上传单个文件的不同部分。

web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2FileUploadExample</display-name>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

Deployment descriptor is self explanatory, just adding Struts 2 filter to intercept the client requests.

部署描述符是不言自明的,仅添加Struts 2过滤器即可拦截客户端请求。

pom.xml

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Struts2FileUploadExample</groupId>
	<artifactId>Struts2FileUploadExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.3.15.1</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

Maven configuration file is also easy to understand and includes only struts-core dependency.

Maven配置文件也很容易理解,并且仅包含struts-core依赖项。

UploadFile.jsp

UploadFile.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags"  prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Upload File Page</title>
</head>
<body>
<h3>Select File to Upload</h3>
<s:form action="UploadFile" method="post" enctype="multipart/form-data">
<s:file label="File" name="file"></s:file>
<s:submit value="Upload"></s:submit>
</s:form>
</body>
</html>

The important points to note in UploadFile.jsp are enctype (multipart/form-data), file element name (file) and action (UploadFile).

UploadFile.jsp中要注意的重要点是enctype(多部分/表单数据),文件元素名称(文件)和操作(UploadFile)。

Before we move to action class implementation, let’s look at the struts.xml configuration file.

在进行动作类实现之前,让我们看一下struts.xml配置文件。

struts.xml

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"https://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.multipart.maxSize" value="104857600" />
	<package name="user" namespace="/" extends="struts-default">
		<action name="upload">
			<result>/UploadFile.jsp</result>
		</action>
		<action name="UploadFile" class="com.journaldev.struts2.actions.UploadFileAction">
			<param name="filesPath">myfiles</param>
			<result name="success">/UploadFileSuccess.jsp</result>
			<result name="input">/UploadFile.jsp</result>

			<interceptor-ref name="defaultStack">
				<param name="fileUpload.maximumSize">10485760</param>
				<param name="fileUpload.allowedTypes">text/plain,image/jpeg</param>
			</interceptor-ref>

		</action>
	</package>

</struts>

Notice that I have set the maximum file size limit in a single request to 100 MB by setting the value of struts.multipart.maxSize to 100*1024*1024.

请注意,通过将struts.multipart.maxSize的值设置为100 * 1024 * 1024,我将单个请求中的最大文件大小限制设置为100 MB。

FileUploadInterceptor default limit for single file size is 2 MB, so I am overriding it for UploadFile action. I am using defaultStack with params maximumSize (10MB) and allowedTypes (txt, jpg) for fileUpload interceptor.

单个文件大小的FileUploadInterceptor默认限制为2 MB,因此我将其替换为UploadFile操作。 我使用defaultStack使用参数MAXIMUMSIZE(10MB)allowedTypes(TXT,JPG格式)文件上传用于拦截。

Now we are ready to look into the action class implementation.

现在,我们准备研究动作类的实现。

UploadFileAction.java

UploadFileAction.java

package com.journaldev.struts2.actions;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;

import org.apache.struts2.util.ServletContextAware;

import com.journaldev.struts2.util.FilesUtil;
import com.opensymphony.xwork2.ActionSupport;

public class UploadFileAction extends ActionSupport implements ServletContextAware{

	private static final long serialVersionUID = -4748500436762141116L;

	@Override
	public String execute(){
		System.out.println("File Name is:"+getFileFileName());
		System.out.println("File ContentType is:"+getFileContentType());
		System.out.println("Files Directory is:"+filesPath);
		try {
			FilesUtil.saveFile(getFile(), getFileFileName(), context.getRealPath("") + File.separator + filesPath);
		} catch (IOException e) {
			e.printStackTrace();
			return INPUT;
		}
		return SUCCESS;
		
	}
	
	private File file;
	private String fileContentType;
	private String fileFileName;
	private String filesPath;
	private ServletContext context;

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public void setFilesPath(String filesPath) {
		this.filesPath = filesPath;
	}

	@Override
	public void setServletContext(ServletContext ctx) {
		this.context=ctx;
	}
	
}

Notice that action class is implementing ServletContextAware interface that contains single method setServletContext(). This is done to get the ServletContext reference in action class and use it to get the web application root directory. This will be used in saving the file from temp directory to another directory inside web application.

注意,操作类正在实现ServletContextAware接口,该接口包含单个方法setServletContext() 。 这样做是为了在操作类中获取ServletContext引用,并使用它来获取Web应用程序的根目录。 这将用于将文件从temp目录保存到Web应用程序内的另一个目录。

Did you noticed filesPath parameter defined for UploadFile action, that’s why we have setFilesPath() method. This method is used by Struts 2 params interceptor to read the params configured in struts.xml file and invoke it’s setter method.

您是否注意到为UploadFile操作定义的filesPath参数,这就是为什么我们有setFilesPath()方法的原因。 Struts 2 params拦截器使用此方法读取struts.xml文件中配置的params并调用它的setter方法。

The three variables that are set by fileUpload and params interceptors are File, file name and content type. If the file element name in request is “pic” then these variables should be – File pic, String picContentType and String picFileName. Since our UploadFile.jsp file element name is “file”, we have variables file, fileFileName and fileContentType with their getter and setters.

由fileUpload和params拦截器设置的三个变量是File,文件名和内容类型。 如果请求中的文件元素名称为“ pic”,则这些变量应为– File pic,String picContentType和String picFileName。 由于我们的UploadFile.jsp文件元素名称为“ file”,因此我们有了变量file,fileFileName和fileContentType以及它们的getter和setter。

FilesUtil is utility class that is used to save the file from temp directory to another directory in the web application.

FilesUtil是实用程序类,用于将文件从temp目录保存到Web应用程序中的另一个目录。

FileUtil.java

FileUtil.java

package com.journaldev.struts2.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FilesUtil {

	public static void saveFile(File file, String fileName, String filesDirectory) throws IOException{
		FileInputStream in = null;
        FileOutputStream out = null;
        
        File dir = new File (filesDirectory);
        if ( !dir.exists() )
           dir.mkdirs();
        
        String targetPath =  dir.getPath() + File.separator + fileName;
        System.out.println("source file path ::"+file.getAbsolutePath());
        System.out.println("saving file to ::" + targetPath);
        File destinationFile = new File ( targetPath);
        try {
            in = new FileInputStream( file );
            out = new FileOutputStream( destinationFile );
            int c;

            while ((c = in.read()) != -1) {
                out.write(c);
            }

        }finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
        
	}
}

The response JSP page after successful file upload code is:

成功上传文件代码后的响应JSP页面是:

UploadFileSuccess.jsp

UploadFileSuccess.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Upload Success Page</title>
</head>
<body>
<h3><s:property value="fileFileName"/> Uploaded Successfully.</h3>
</body>
</html>

Notice the use of fileFileName variable from action class is used in response JSP page.

注意,在响应JSP页面中使用了来自操作类的fileFileName变量。

Our implementation for single file upload is ready, when we execute the application we get following response pages.

我们已经完成了单文件上传的实现,当我们执行应用程序时,我们将获得以下响应页面。

We get following logs in server logs.

我们在服务器日志中获得以下日志。

File Name is:IMG_2053.JPG
File ContentType is:image/jpeg
Files Directory is:myfiles
source file path ::/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/Struts2FileUploadExample/upload_e287e5cd_17be_4f3f_a034_b21ae19da743_00000006.tmp
saving file to ::/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Struts2FileUploadExample/myfiles/IMG_2053.JPG

Above logs confirm that fileUpload interceptor uploads file in temp directory and rename it with .tmp extension. The same file is copied from there to our specified location.

以上日志确认fileUpload拦截器将文件上传到temp目录中,并以.tmp扩展名重命名。 相同的文件从那里复制到我们指定的位置。

Struts 2多个文件上传 (Struts 2 Multiple File Upload)

If you understood how single file upload works, then multiple file upload is very easy. FileUploadInterceptor saves all the files in request to temp directory and we can use Array or List to get their reference in action classes.

如果您了解单文件上传的工作原理,那么多文件上传非常简单。 FileUploadInterceptor将请求中的所有文件保存到temp目录中,我们可以使用Array或List在操作类中获取它们的引用。

UploadMultipleFile.jsp

UploadMultipleFile.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags"  prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Upload File Page</title>
</head>
<body>
<h3>Select File to Upload</h3>
<s:form action="UploadMultipleFile" method="post" enctype="multipart/form-data">
<s:file label="File 1:" name="file"></s:file>
<s:file label="File 2:" name="file"></s:file>
<s:file label="File 3:" name="file"></s:file>
<s:submit value="Upload"></s:submit>
</s:form>
</body>
</html>

Notice that all the file elements name are same.

请注意,所有文件元素名称均相同。

UploadMultipleFileAction.java

UploadMultipleFileAction.java

package com.journaldev.struts2.actions;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.servlet.ServletContext;

import org.apache.struts2.util.ServletContextAware;

import com.journaldev.struts2.util.FilesUtil;
import com.opensymphony.xwork2.ActionSupport;

public class UploadMultipleFileAction extends ActionSupport implements ServletContextAware{

	private static final long serialVersionUID = -4748500436762141236L;

	@Override
	public String execute(){
		System.out.println("No of files="+getFile().length);
		System.out.println("File Names are:"+Arrays.toString(getFileFileName()));
		
		for(int i=0; i < getFile().length; i++){
		System.out.println("File Name is:"+getFileFileName()[i]);
		System.out.println("File ContentType is:"+getFileContentType()[i]);
		System.out.println("Files Directory is:"+filesPath);
		try {
			FilesUtil.saveFile(getFile()[i], getFileFileName()[i], context.getRealPath("") + File.separator + filesPath);
		} catch (IOException e) {
			e.printStackTrace();
			return INPUT;
		}
		}
		return SUCCESS;
		
	}
	
	private File[] file;
	private String[] fileContentType;
	private String[] fileFileName;
	private String filesPath;
	/**
	 * We could use List also for files variable references and declare them as:
	 * 
	 * private List<File> file = new ArrayList<File>();
	 * private List<String> fileContentType = new ArrayList<String>();
	 * private List<String> fileFileName = new ArrayList<String>();
	 */
	
	
	private ServletContext context;


	public File[] getFile() {
		return file;
	}

	public void setFile(File[] file) {
		this.file = file;
	}

	public String[] getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String[] fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String[] getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String[] fileFileName) {
		this.fileFileName = fileFileName;
	}

	public void setFilesPath(String filesPath) {
		this.filesPath = filesPath;
	}

	@Override
	public void setServletContext(ServletContext ctx) {
		this.context=ctx;
	}
	
}

Action class is similar as single upload, except that the variables are now array or list to hold multiple values. We are iterating the array and saving each file to specific directory.

动作类类似于单次上传,不同之处在于变量现在是数组或列表,可以容纳多个值。 我们正在迭代数组并将每个文件保存到特定目录。

UploadMultipleFileSuccess.jsp

UploadMultipleFileSuccess.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Upload Success Page</title>
</head>
<body>
<h3><s:property value="fileFileName"/> Uploaded Successfully.</h3>
</body>
</html>

To configure them, just add below action elements in existing struts.xml file.

要配置它们,只需在现有的struts.xml文件中在action元素下方添加。

<action name="uploadMultiple">
	<result>/UploadMultipleFile.jsp</result>
</action>

<action name="UploadMultipleFile"
	class="com.journaldev.struts2.actions.UploadMultipleFileAction">
	<param name="filesPath">myfiles</param>
	<result name="success">/UploadMultipleFileSuccess.jsp</result>
	<result name="input">/UploadMultipleFile.jsp</result>

	<interceptor-ref name="defaultStack">
		<param name="fileUpload.maximumSize">10485760</param>
		<param name="fileUpload.allowedTypes">text/plain,image/jpeg</param>
	</interceptor-ref>

</action>

Now when we execute multiple file upload action, we get following response pages.

现在,当我们执行多个文件上传操作时,我们得到以下响应页面。

We get following log snippet in the server log file.

我们在服务器日志文件中获得以下日志片段。

No of files=3
File Names are:[ETERNA_Movie_List.txt, DSC05510.JPG, IMG_2053.JPG]
File Name is:ETERNA_Movie_List.txt
File ContentType is:text/plain
Files Directory is:myfiles
source file path ::/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/Struts2FileUploadExample/upload_e287e5cd_17be_4f3f_a034_b21ae19da743_00000007.tmp
saving file to ::/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Struts2FileUploadExample/myfiles/ETERNA_Movie_List.txt
File Name is:DSC05510.JPG
File ContentType is:image/jpeg
Files Directory is:myfiles
source file path ::/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/Struts2FileUploadExample/upload_e287e5cd_17be_4f3f_a034_b21ae19da743_00000008.tmp
saving file to ::/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Struts2FileUploadExample/myfiles/DSC05510.JPG
File Name is:IMG_2053.JPG
File ContentType is:image/jpeg
Files Directory is:myfiles
source file path ::/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/Struts2FileUploadExample/upload_e287e5cd_17be_4f3f_a034_b21ae19da743_00000009.tmp
saving file to ::/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Struts2FileUploadExample/myfiles/IMG_2053.JPG

That's all for Struts 2 file upload example, you can download the complete project from below link and learn more about it.

这就是Struts 2文件上传示例的全部内容,您可以从下面的链接下载完整的项目并了解更多信息。

翻译自: https://www.journaldev.com/2192/struts-2-file-upload-example

struts2登录注册示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值