Struts 2动态调用使用通配符和感叹号两种方法,感叹号官方不建议使用,所以想用通配符的方法,在2.5之前的版本都是直接配置即可:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<package name="demo" extends="struts-default">
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="*Action" class="com.ymk.action.userAction" method="{1}">
<result name="success">/update.jsp</result>
<result name="error">/index.jsp</result>
</action>
</package>
</struts>
当上配置在Struts 2.5 的环境下运行的时候,会出现异常:
HTTP Status 404 - There is no Action mapped for namespace [/] and action name [user_add] associated with context path [/struts].
网上很多教程说加上 常量配置<constant name="struts.enable.DynamicMethodInvocation" value="true" />即可,因为默认值为false,但试了还是错误。
正确的解决方法是在配置文件中加上<global-allowed-methods>regex:.*</global-allowed-methods>
<?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>
<package name="Lyu" extends="struts-default" >
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="user_*" class="com.ymk.action.testAction" method="{1}">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
另:2.5的jar包将xwork-core包合并到了struts-core下,因此配置过滤器时的路径改为
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter