java struts2入门学习---文件下载的二种方式(一)

2014-11-24 02:40:50 · 作者: · 浏览: 2
一.关于文件 下载:
文件下载的核心思想即是将文件从一个地方拷贝到另一个地方.
1.传统方式:
  在Action中加入大量servlet api 操作.优点是好理解,缺点是耦合度高。
2.stream方式:
使用struts2中的stream拦截器进行操作
二.实例:
我这里用的是maven,贴出pom.xml:
复制代码
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
com.amos
struts2_learn
war
0.0.1-SNAPSHOT
struts2_learn Maven Webapp
http://maven.apache.org
junit
junit
4.11
test
org.apache.struts
struts2-core
2.3.16
org.apache.commons
commons-io
1.3.2
jstl
jstl
1.1.2
provided
taglibs
standard
1.1.2
struts2_learn
复制代码
1.使用传统方式实现文件下载:
DownloadAction.java
复制代码
package download;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* @ClassName: DownloadAction
* @Description: 文件下载
* @author: amosli
* @email:amosli@infomorrow.com
* @date Feb 13, 2014 1:22:23 AM
*/
public class DownloadAction extends ActionSupport {
private static final long serialVersionUID = -5609061774548242181L;
private String fileName;//文件名称
public void setFileName(String fileName) {
if (ServletActionContext.getRequest().getMethod().equals("GET")) {
try {
byte[] bytes = fileName.getBytes("ISO8859-1");//将get方式提交的中文进行处理,即将编码由ISO8859-1转为utf-8
fileName = new String(bytes, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
this.fileName = fileName;
}
// 下载
public String execute() throws Exception {
// 1.传统下载方式
// 取得HttpServletResponse对象
HttpServletResponse response = ServletActionContext.getResponse();
// 取得ServletContext对象
ServletContext context = ServletActionContext.getServletContext();
// 通知 浏览器以下载方式打开文件
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
// 取得需要下载文件的根目录
String realPath = context.getRealPath("/WEB-INF/download");
// 构造子节输入流
InputStream is = new FileInputStream(realPath + "/" + fileName);
// 构造子节输出流
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = is.read(b)) > 0) {
os.write(b, 0, len);
}
is.close();
os.close();
return SUCCESS;
}
}
复制代码
download. jsp
复制代码
<%@ page language="java" contentType="text/ html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri='http://java.sun.com/jsp/jstl/core' prefix="c" %>
Insert title here
英文需要编码
style="text-decoration: none">
building.jpg
<%--
复制代码
download_struts.xml