Action调用指定方法处理业务,如果method属性指定了方法,就调用指定的方法,如果没有置method属性,则调用默认的execute。
设置的方法是固定的,如果一个Action中有多个处理业务的方法,比如login()、register(),要根据需要来调用方法,这就不方便了。
可以给一个类配置多个Action:
<action name="LoginAction" class="action.HandlerAction" method="login"> </action> <action name="RegisterAction" class="action.HandlerAction" method="register"> </action>
class相同,name、method不同,这样可以调用同一个类中的不同方法。
但方法很多时,需要配置大量的action,很麻烦。
动态方法调用(DMI,Dynamic Method Invocation)可以解决此问题。
动态方法调用有2种实现方式。
1、常量配置
<struts> <!-- 开启动态方法调用 --> <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <package name="action" namespace="/" extends="struts-default"> <global-allowed-methods>login,register</global-allowed-methods> <action name="HandlerAction" class="action.HandlerAction"> <result name=""></result> <result name=""></result> <allowed-methods>login,register</allowed-methods> </action> </package> </struts>
在常量配置中开启动态方法调用,在<allowed-methods>中配置当前action可以动态调用的方法,或者在<global-allowed-methods>中配置整个包下所有action可以动态调用的方法。不必再使用method属性。
struts-default.xml中自带的配置:
<global-allowed-methods>execute,input,back,cancel,browse,save,delete,list,index</global-allowed-methods>
使用 action名!方法名 的形式来引用,action名指定Action,方法名指定要调用的方法。
<form action="HandlerAction!login"></form> <form action="HandlerAction!register"></form>
提交给HandlerAction来处理,指定调用方法为login|register。
这种方式有个很大的缺点:
URL中有“!”,搜索引擎不愿意收录这种带有乱七八糟符号的网址,不利于网站的推广、排名。
所以一般不用这种方式。
2、使用通配符*
<struts> <package name="action" namespace="/" extends="struts-default"> <global-allowed-methods>login,register</global-allowed-methods> <action name="HandlerAction_*" class="action.HandlerAction" method="{1}"> <result name=""></result> <result name=""></result> <allowed-methods>login,register</allowed-methods> </action> </package> </struts>
引用方式:
HandlerAction_login
HandlerAction_register
*表示一个或多个字符,先在<action>的name中使用一个或多个通配符*,之后就可以在action的class、method、子元素<result>中使用{n}来引用第n个*。
注意通配符是写在<action>的name属性中的。
此种方式不需要在常量配置中开启动态方法调用,但仍要指定可以动态调用的方法,需要使用method属性。
下划线只是为了隔开action、方法名,方便阅读,可以换为其他字符、字符串。
可以这样写:
<action name="*Action" class="action.HandlerAction" method="{1}"> <result name=""></result> <result name=""></result> <allowed-methods>login,register</allowed-methods> </action>
loginAction
registerAction
也可以这样写:
<action name="*Action" class="action.{1}Action">
<result name=""></result>
<result name=""></result>
</action>
这里未指定method,默认调用execute,也可以自己指定。
LoginAction
RegisterAction