1. FileDownloadAction
package elia;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.Action;
public class FileDownloadAction implements Action{
// inputpath是依赖注入的属性,可以在配置文件struts.xml中动态指定该属性的值
private String inputpath;
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
// 依赖注入inputpath属性的set方法
public void setInputpath(String inputpath) {
this.inputpath = inputpath;
}
// 下载用的action应该返回InputStream实例,该方法对应struts.xml里面result的InputName属性的值(targetFile)
public InputStream getTargetFile()throws Exception{
//return ServletActionContext.getServletContext().getResourceAsStream(inputpath);
return new BufferedInputStream(new FileInputStream(inputpath));
}
@Override
public String execute() throws Exception {
// 下载前的授权控制
if(userName != null && userName.equals("elia")){
return SUCCESS;
}
return LOGIN;
}
}
2.struts.xml
<?xml version="1.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.i18n.encoding" value="Windows-31J" />
<constant name="struts.multipart.saveDir" value="f:/upload" />
<package name="elia" extends="struts-default">
<action name="DownloadAction" class="elia.FileDownloadAction">
<param name="inputpath">F:/jndi-1_2_1.zip</param>
<result name="success" type="stream">
<param name="contentType">zip</param>
<param name="inputName">targetFile</param>
<param name="contentDisposition">filename="jndi-1_2_1.zip"</param>
<!-- <param name="bufferSize">1024*1024</param> -->
</result>
<result name="login">/pages/login.jsp</result>
</action>
</package>
</struts>
3.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Login</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>
4.login.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Sign on</title>
</head>
<body>
<s:form action="DownloadAction">
<s:textfield name="userName" label="userName"/>
<s:submit />
</s:form>
</body>
</html>
ps:
调试时出现Can not find a java.io.InputStream with the name [targetFile] in the invocation stack错误,是因为getTargetFile()方法没有取到值,可能的原因:
1.action里面定义的inputpath变量与struts.xml里面定义的inputpath变量
不一致,刚开始struts.xml里面写成inputPath
2.在getTargetFile()方法里面用return ServletActionContext.getServletContext().getResourceAsStream(inputpath);
来获取InputStream,取到的值为null,不知道为什么会取不到值!!