それをダウンロードする –
Struts2-Download-File-Example.zip
ユーザーがファイルをダウンロードできるようにカスタム結果タイプを使用する方法を示すStruts 2の例。
1.アクション
Actionクラスで、InputStreamデータ型とそのゲッターメソッドを宣言しました。
package com.mkyong.common.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport{
private InputStream fileInputStream;
public InputStream getFileInputStream() {
return fileInputStream;
}
public String execute() throws Exception {
fileInputStream = new FileInputStream(new File("C:\\downloadfile.txt"));
return SUCCESS;
}
}
2.表示ページ
通常のページで、ファイルをダウンロードするためのダウンロードリンクがあります。
-
downloadPage.jsp **
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<h1>Struts 2 download file example</h1>
<s:url id="fileDownload" namespace="/" action="download" ></s:url>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-2836379775501347"
data-ad-slot="8821506761"
data-ad-format="auto"
data-ad-region="mkyongregion"></ins>
<script>
(adsbygoogle = window.adsbygoogle ||[]).push({});
</script><h2>Download file - <s:a href="%{fileDownload}">fileABC.txt</s:a>
</h2>
</body>
</html>
3. struts.xml
ダウンロードファイルの詳細を、自明のものとして定義します。
<param name = “inputName”>
valueは、ActionのInputStreamプロパティの名前です。
詳細は、http://struts.apache.org/2.x/docs/stream-result.html[Struts 2 Stream Result documentation]を参照してください。
-
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.devMode" value="true"/>
<package name="default" namespace="/" extends="struts-default">
<action name="">
<result name="success">pages/downloadPage.jsp</result>
</action>
<action name="download" class="com.mkyong.common.action.DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="fileABC.txt"</param>
<param name="bufferSize">1024</param>
</result>
</action>
</package>
</struts>
リファレンス
-
//struts/struts-download-file-from-website-example/
-
//java/how-to-download-file-from-website-java-jsp/
-
http://struts.apache.org/2.x/docs/how-can-we-return-a-text-string-as-the-response.html