错误:
HTTP Status 404 - There is no Action mapped for namespace [/] and action name [helloworld_add] associated with context path [/Struts2Demo].
解决方法:
DMI(Dynamic Method Invocation,动态方法调用),动态方法调用是为了解决一个 Action 对应多个请求的处理,以免 Action 太多。有三种方法:
- 指定 method 属性;
- 感叹号方式(官方不推荐);
- 通配符方式。
在 Struts 2.5 中,为了限制 DMI,默认启用了严格的方法访问,增加了新的标签(strict-method-invocation)设置,strict-method-invocation 的值默认为 true 。
Struts 2.5 ,Struts 官网文档建议使用的头部信息(struts.xml 如下):
Struts 2.5 DTD
<?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>
Struts 2.5 中 SMI(strict-method-invocation)的使用方式:
在 package 中添加属性 strict-method-invocation="false" 就可以正常使用通配符了;
设置 strict-method-invocation="true" 的情况下,设置 allowed 标签、global-allowed-methods 标签,只在设置的标签中起作用,如:
SMI via struts.xml
<package ...>
...
<global-allowed-methods>execute,input,back,cancel,browse</global-allowed-methods>
...
<action name="Bar">
<allowed-methods>foo,bar</allowed-methods>
</action>
...
</package>
示例代码:
- strict-method-invocation="false"
<package name="default" namespace="/" extends="struts-default" strict-method-invocation="false">
<action name="*_*" class="com.imooc.action.{1}Action" method="{2}">
<result>/result.jsp</result>
<result name="add">/{2}.jsp</result>
<result name="update">/{2}.jsp</result>
</action>
</package>
- strict-method-invocation="true",同时设置 <allowed-methods>
<package name="default" namespace="/" extends="struts-default"
strict-method-invocation="true">
<action name="*_*" class="com.imooc.action.{1}Action" method="{2}">
<result>/result.jsp</result>
<result name="add">/{2}.jsp</result>
<result name="update">/{2}.jsp</result>
<allowed-methods>add,update</allowed-methods>
</action>
</package>
- strict-method-invocation="true",同时设置 <global-allowed-methods> 标签
<package name="default" namespace="/" extends="struts-default"
strict-method-invocation="true">
<global-allowed-methods>add,update</global-allowed-methods>
<action name="*_*" class="com.imooc.action.{1}Action" method="{2}">
<result>/result.jsp</result>
<result name="add">/{2}.jsp</result>
<result name="update">/{2}.jsp</result>
</action>
</package>
参考链接:
//www.greatytc.com/p/3aaadaef5c80
https://struts.apache.org/docs/action-configuration.html