今天在玩Struts2的下载功能时,遇到了一些低级错误,已经从中学到一点东西,再次分享一下。
下载页面代码down.jsp如下:
<body>
<h1>原始下载</h1>
<ul>
<li>
下载疯狂java联盟的Logo:
<a href="download.action">下载图形文件</a>
</li>
</ul>
</body>
处理此请求的action为FileDownloadAction,代码如下:
public class FileDownloadAction extends ActionSupport{ private String inputPath; public void setInputPath(String value) { inputPath = value; } public String getInputPath() { return inputPath; } public InputStream getTargetFile() throws Exception { return ServletActionContext.getServletContext().getResourceAsStream(inputPath); } public String execute() { return SUCCESS; } }
配置文件内容:<struts> <package name="downloadfile" extends="struts-default"> <action name="download" class="com.struts2.download.action.FileDownloadAction"> <param name="inputPath">images/wjc_logo.jpg</param> <result name="success" type="stream"> <param name="contentType">image/jpg</param> <param name="inputName">targetFile</param> <param name="contentDisposition">attachment;filename="wjc_logo.jpg"</param> <param name="bufferSize">4096</param> </result> </action> </package> </struts>
项目文件路径:
代码写完后启动服务器时出现如下错误:原因是配置<package>时没有继承struts-default默认包
系统正常启动后又出现如下异常:Caused by: Unable to load configuration. - action - file:/D:/ProgramFiles/apache-tomcat-7.0.39/apache-tomcat-7.0.39/webapps/struts/WEB-INF/classes/com/struts2/download/action/download.xml:8:83 at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:70) at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:445) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:489) ... 19 more
type Exception report message Can not find a java.io.InputStream with the name [targetFile] in the invocation stack. Check the <param name="inputName"> tag specified for this action. description The server encountered an internal error that prevented it from fulfilling this request. exception java.lang.IllegalArgumentException: Can not find a java.io.InputStream with the name [targetFile] in the invocation stack. Check the <param name="inputName"> tag specified for this action.
异常原因是找不到要下载的资源文件,最后才发现下载的文件搞错了。