在 Struts2 中實現文件下載並記錄用戶點擊行為,核心思路是通過 Action 方法處理下載請求,在方法執行前/後記錄日誌或更新數據庫。
public class DownloadAction extends ActionSupport {
private String fileName; // 接收前台傳遞的文件標識
private InputStream inputStream; // 文件流
// Getter/Setter 省略
public String execute() {
// 1. 記錄下載日誌:用戶IP、時間、文件名、User-Agent 等
logDownload(fileName);
// 2. 根據 fileName 定位文件路徑,設置 inputStream
inputStream = new FileInputStream(getRealPath(fileName));
return SUCCESS;
}
}
struts.xml:
<action name="download" class="com.example.DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">4096</param>
</result>
</action>
<a href="download.action?fileName=report.pdf">下載報告</a>
Action 中聲明對應屬性(如 private String fileName; + Getter/Setter),Struts2 會自動將請求參數 fileName 注入。同理可傳遞 id、token 等業務參數。
編寫自定義攔截器 DownloadLogInterceptor,在 intercept() 中記錄下載動作,配置在 struts.xml 的 <interceptor-stack> 中,實現與業務 Action 解耦。
此模式符合 Struts2 「Action 處理業務、Result 處理視圖/流」的設計哲學,清晰可維護。