You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Struts 2.5.14新增非hello名称Action失败问题求助

解决Struts 2.5.14中自定义Action无法访问的问题

根据你描述的情况——只有hello Action能正常工作,contracts Action提示映射不存在,结合Struts 2.5的特性和你的配置来看,问题大概率出在**Strict Method Invocation(SMI,严格方法调用)**上,这是Struts 2.5默认开启的安全特性。

问题根源

Struts 2.5默认启用SMI,它会限制Action中可被调用的方法:

  • 默认允许的方法只有execute、input、back、cancel、browse这些标准方法
  • 你的hello Action用的是execute方法,属于默认允许范围,所以能正常运行
  • 而contracts Action指定了method="contracts",这个自定义方法不在默认允许列表里,被SMI拦截后就会抛出"There is no Action mapped for action name contracts"的错误(本质是方法不允许被调用,而非Action没配置)

解决方案

这里有两种可行的解决方式,推荐第一种(更安全):

1. 为每个Package配置允许调用的方法

在你的home和view包中,添加<allowed-methods>标签,明确指定允许调用的方法。修改后的struts.xml示例:

<struts>
    <package name="home" namespace="/home" extends="struts-default">
        <result-types>
            <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult"/>
        </result-types>
        <action name="hello" class="action.HelloWorldAction" method="execute">
            <result type="tiles">menu</result>
        </action>
        <action name="contracts" class="action.ViewContractsAction" method="contracts">
            <result type="tiles">hello</result>
        </action>
        <!-- 添加允许的方法 -->
        <allowed-methods>execute, contracts</allowed-methods>
    </package>

    <package name="view" namespace="/view" extends="struts-default">
        <result-types>
            <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult"/>
        </result-types>
        <action name="hello" class="action.ViewContractsAction" method="execute">
            <result type="tiles">contracts</result>
        </action>
        <action name="contracts" class="action.ViewContractsAction" method="contracts">
            <result type="tiles">contracts</result>
        </action>
        <!-- 添加允许的方法 -->
        <allowed-methods>execute, contracts</allowed-methods>
    </package>
</struts>

2. 全局关闭SMI(不推荐生产环境)

如果你只是在测试环境想快速验证,可以在<struts>根节点下添加常量关闭SMI,但这种方式会降低应用安全性,不建议在生产环境使用:

<struts>
    <!-- 关闭动态方法调用和严格方法调用 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"/>
    <constant name="struts.strict.method.invocation" value="false"/>

    <!-- 你的package配置... -->
</struts>

额外检查点

除了SMI配置,还要确认你的ViewContractsAction类中的contracts方法符合Struts2的规范:

public class ViewContractsAction extends ActionSupport {
    // 确保方法是public、无参数、返回String类型
    public String contracts() {
        // 你的业务逻辑
        return SUCCESS;
    }
}

完成以上配置后,重启Tomcat,应该就能正常访问../home/contracts和../view/contracts了。

内容的提问来源于stack exchange,提问作者Jitendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:15:43