Struts 1 專案常需在進入 Action 前進行通用預處理:字元編碼設定、登入檢查、IP 存取控制等。本文提供一個繼承 RequestProcessor 的自訂預處理器,實現 IP 白名單驗證,並詳解配置步驟與擴充要點。
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; // 繼續標準流程
}
}
<controller processorClass="com.example.struts.MyRequestProcessor"/>
放置於 `
<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>
| 維度 | Servlet Filter | RequestProcessor 子類 |
|---|---|---|
| 攔截範圍 | 所有請求 (含靜態資源、JSP、Struts) | 僅 Struts 處理的請求 (*.do 等) |
| Struts 整合度 | 低,無法直接存取 ActionForm/Mapping | 高,可存取完整 Struts 內部物件 |
| 配置複雜度 | web.xml 簡單 | struts-config.xml 專屬 |
| 適用場景 | 編碼設定、登入檢查、日誌、跨框架通用邏輯 | Struts 專屬業務預處理 (權限、工作流、資料預載) |
繼承 RequestProcessor 覆寫 processPreprocess() 是 Struts 1 實現請求級預處理的標準擴充點。IP 白名單僅為範例,同樣模式可實現:用戶權限矩陣驗證、多租戶資料隔離、請求參數清洗、API 限流計數等。配合外部化配置,即可構建靈活可維護的存取控制體系。