首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Struts2 文件下載:如何追蹤用戶點擊下載鏈接並獲取參數

     編輯:程式設計綜合問答

在 Struts2 中實現文件下載並記錄用戶點擊行為,核心思路是通過 Action 方法處理下載請求,在方法執行前/後記錄日誌或更新數據庫。

實現方案

  1. 定義下載 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;
        }
    }
    
  2. Struts 配置 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>
    
  3. 前台下載鏈接:
    <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 處理視圖/流」的設計哲學,清晰可維護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved