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

Struts 2.5 通配符映射 Action 方法常見錯誤與 allowed-methods 解決

     編輯:Java 綜合教學

Struts 2.5 通配符映射 Action 方法常見錯誤與 allowed-methods 解決

典型配置與報錯


<package name="shop" namespace="/" extends="struts-default">
    <action name="user_*" class="userAction" method="{1}">
        <result name="success">/WEB-INF/jsp/login.jsp</result>
    </action>
</package>

訪問 /user_login 時報錯:

There is no Action mapped for namespace [/] and action name [user_login] associated with context path [/shop].

排查清單(按概率)

  1. URL 拼寫、大小寫、namespace 是否正確
  2. struts.xml 配置:action name、class、method、result 名稱
  3. Action 類方法名、返回值與 result 對應
  4. 結果頁面路徑是否存在

深層原因:Struts 2.3+ 安全機制

Struts 2.3 引入 方法白名單機制,通配符映射的動態方法需顯式聲明允許訪問,否則被安全攔截器攔截。

解決方案:添加 <allowed-methods>


<action name="user_*" class="userAction" method="{1}">
    <result name="success">/WEB-INF/jsp/login.jsp</result>
    <allowed-methods>login,register,logout</allowed-methods>  <!-- 關鍵:聲明允許的方法 -->
</action>
  • 多個方法用逗號分隔
  • 支持通配符:<allowed-methods>*</allowed-methods>(不推薦生產)

相關配置項對比

版本差異提示

  • Struts 2.3 之前:無需 allowed-methods,直接可用
  • Struts 2.3+:必須配置allowed-methods,否則 404/映射錯誤
  • Struts 2.5:同 2.3,嚴格執行

最佳實踐

  1. 每個通配符 Action 精確配置 allowed-methods
  2. 禁用 DynamicMethodInvocation 減少攻擊面
  3. 考慮遷移到 REST 風格或 SpringMVC(Struts 2 維護模式)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
配置項作用建議值
struts.enable.DynamicMethodInvocation啟用 action!method 風格動態調用false(通配符模式下)
<allowed-methods>通配符/REST 模式方法白名單必配,精確列出方法名