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

解決 Struts2 攔截器導致 eWebEditor 上傳失效的問題

     編輯:Java 相關知識

現象

整合線上編輯器 eWebEditor 後,圖片/附件上傳功能失效(無反應或 404),懷疑 Struts2 的 FilterDispatcher 攔截了上傳請求。

根因分析

預設 web.xml 將 Struts2 映射至 /*:

<filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

導致所有請求(含 eWebEditor 的上傳 Servlet /ewebeditor/upload.jsp 等)先經 Struts2 處理,若無對應 Action 則回傳 404 或被安全攔截器阻擋。

快速修正:縮小攔截範圍

將 Struts2 映射限定在特定前綴(如 /web/*):

<filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/web/*</url-pattern>
</filter-mapping>

同步調整:

  • 所有 JSP 搬至 /web/ 目錄下
  • 所有 .action 請求路徑加上 /web/ 前綴
  • eWebEditor 置於根目錄或非 /web/ 路徑,避開 Struts2 攔截

更優雅的方案:排除靜態資源與特定路徑

Struts 2.1.6+ 支援 struts.action.excludePattern(struts.xml 或 struts.properties):

<constant name="struts.action.excludePattern" value="/ewebeditor/.*|/ckeditor/.*|/static/.*" />

或在 web.xml 使用 <dispatcher>REQUEST</dispatcher> 搭配 FilterChain 手動放行:

public class StrutsFilterExclude extends FilterDispatcher {
    private static final String[] EXCLUDE_PREFIX = {"/ewebeditor/", "/static/"};
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String uri = request.getRequestURI();
        for (String prefix : EXCLUDE_PREFIX) {
            if (uri.startsWith(request.getContextPath() + prefix)) {
                chain.doFilter(req, res); // 直接放行
                return;
            }
        }
        super.doFilter(req, res, chain);
    }
}

然後在 web.xml 替換 filter-class 為自訂類別。

建議

  • 新專案優先採用 excludePattern 配置,零代碼入侵。
  • 舊專案若無法升級 Struts 版本,採用「前綴隔離」法(/web/*)最穩妥。
  • 長遠規劃:前端編輯器遷移至 CKEditor 5 / TinyMCE 等現代元件,採用 RESTful 上傳 API,徹底脫離傳統 Servlet 依賴。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved