首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Struts 1 實用請求過濾器:IP 白名單存取控制完整實作

     編輯:Java 相關知識

Struts 1 專案常需在進入 Action 前進行通用預處理:字元編碼設定、登入檢查、IP 存取控制等。本文提供一個繼承 RequestProcessor 的自訂預處理器,實現 IP 白名單驗證,並詳解配置步驟與擴充要點。

核心實作:MyRequestProcessor

package com.example.struts;

import javax.servlet.http.*;
import org.apache.struts.action.RequestProcessor;

public class MyRequestProcessor extends RequestProcessor {

    // 允許的 IP 前綴清單 (可從配置檔讀取)
    private static final String[] ALLOWED_PREFIXES = {"126.", "192.168.", "10."};

    @Override
    protected boolean processPreprocess(HttpServletRequest request,
                                        HttpServletResponse response) {
        String remoteHost = request.getRemoteHost(); // 或 getRemoteAddr()
        boolean allowed = false;

        if (remoteHost != null) {
            for (String prefix : ALLOWED_PREFIXES) {
                if (remoteHost.startsWith(prefix)) {
                    allowed = true;
                    break;
                }
            }
        }

        if (!allowed) {
            try {
                // 導向錯誤頁或回傳 403
                response.sendRedirect(request.getContextPath() + "/iperror.jsp");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false; // 阻斷後續處理
        }

        System.out.println("-- IP 驗證通過: " + remoteHost + " --");
        return true; // 繼續標準流程
    }
}

struts-config.xml 配置替換預設 RequestProcessor

<controller processorClass="com.example.struts.MyRequestProcessor"/>

放置於 `` 根元素下,即可全域生效。

web.xml 確保 Struts 控制器載入

<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

擴充建議:將白名單外部化配置

public class MyRequestProcessor extends RequestProcessor {
    private List<String> allowedPrefixes = new ArrayList<>();

    @Override
    public void init(HttpServlet servlet) throws ServletException {
        super.init(servlet);
        String config = servlet.getInitParameter("allowedIPs");
        if (config != null) {
            for (String ip : config.split(",")) {
                allowedPrefixes.add(ip.trim());
            }
        } else {
            allowedPrefixes.add("127.0.0.1"); // 預設本機
        }
    }

    @Override
    protected boolean processPreprocess(HttpServletRequest req, HttpServletResponse resp) {
        String host = req.getRemoteAddr();
        boolean ok = allowedPrefixes.stream().anyMatch(host::startsWith);
        if (!ok) {
            try { resp.sendRedirect(req.getContextPath() + "/403.jsp"); } catch (IOException e) { e.printStackTrace(); }
            return false;
        }
        return true;
    }
}

struts-config.xml 新增初始化參數:

<controller processorClass="com.example.struts.MyRequestProcessor">
    <set-property property="allowedIPs" value="126.,192.168.,10."/>
</controller>

對比:Filter vs RequestProcessor

維度Servlet FilterRequestProcessor 子類
攔截範圍所有請求 (含靜態資源、JSP、Struts)僅 Struts 處理的請求 (*.do 等)
Struts 整合度低,無法直接存取 ActionForm/Mapping高,可存取完整 Struts 內部物件
配置複雜度web.xml 簡單struts-config.xml 專屬
適用場景編碼設定、登入檢查、日誌、跨框架通用邏輯Struts 專屬業務預處理 (權限、工作流、資料預載)

總結

繼承 RequestProcessor 覆寫 processPreprocess() 是 Struts 1 實現請求級預處理的標準擴充點。IP 白名單僅為範例,同樣模式可實現:用戶權限矩陣驗證、多租戶資料隔離、請求參數清洗、API 限流計數等。配合外部化配置,即可構建靈活可維護的存取控制體系。

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