更新到 Struts 2.5 后,通配符动作映射不再有效

Wildcard Action Mapping no longer working after updating to Struts 2.5

我的应用程序 struts.xml 中有以下操作映射,它与 Struts 2.3.28.1 一起工作得很好;调用由 x.ApplicationHandler.edit 方法处理的 /editApplication 操作。

<action name="*Application" class="x.ApplicationHandler" method="{1}">
    <result name="input">/WEB-INF/application.jsp</result>
    <result name="success" type="redirectAction">
        <param name="actionName">browseApps</param>
    </result>
</action>   

升级到 Struts 2.5 后,这不再有效。尝试调用 /editApplication 操作显示 404 错误:

HTTP Status 404 - There is no Action mapped for namespace [/] and action name [editApplication]

我查看了 Struts 2.5 发行说明,没有看到任何关于基于通配符的动作映射工作方式更新的提及。是否有任何原因导致此配置不再有效?

它是 Strict Method Invocation 并且因为 Struts 2.5 它是默认启用的。

来自关于 SMI 和通配符映射的文档:

When using wildcard mapping in actions' definitions SMI works in two ways:

  • SMI is disabled - any wildcard will be substituted with the default RegEx, ie.: <action name="Person*" method="perform*"> will be translated into allowedMethod = "regex:perform([A-Za-z0-9_$]*)".
  • SMI is enabled - no wildcard substitution will happen, you must strictly define which methods can be accessed by annotations or <allowed-method/> tag.

您可以根据 <package>.

禁用它
<package strict-method-invocation="false">

或者您可以使用 <allowed-methods> 标记为每个操作添加允许的方法名称。

<action name="*Application" class="x.ApplicationHandler" method="{1}">
    <result name="input">/WEB-INF/application.jsp</result>
    <result name="success" type="redirectAction">
        <param name="actionName">browseApps</param>
    </result>

    <allowed-methods>firstMethod, secondMethod, thirdMethod</allowed-methods>
</action>

或使用 <global-allowed-methods> 标签为每个包添加允许的方法名称。

<package extends="struts-default">

    <global-allowed-methods>firstMethod, secondMethod, thirdMethod</global-allowed-methods>

</package>

注意 为了在 struts.xml 中使用上述标签,您必须将 DTD 定义更新为 2.5.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
...
</struts>

struts2-convention-plugin 中还有 @AllowedMethods 注释,允许操作指定允许的操作方法。

This annotation can be used directly on Action classes or in the package-info.java class in order to specify global allowed methods for all sub-packages.