Struts2 url中包含感嘆號實現動態方法呼叫
Struts2的動態方法呼叫(Dynamic method Invoc)概括起來有三種方式,下面介紹:
1、第一種方式:設定method屬性
在Action類中定義一個簽名與execute方法相同、只是名字不同的方法,如定義為:
public String login() throws Exception{}
然後在struts.xml檔案中加一個<action>元素,並設定它的method屬性。程式碼如下(核心程式碼):
<action name="loginMethod"
class="com.polaris.LoginAction" method="login">
<result>/result.jsp</result>
<result name="error">/error.jsp</result>
</action>
清單1:struts.xml部分內容
然後在JSP中表單的action設定為loginMethod。這樣,Struts2就會去呼叫LoginAction中的loigin方法,而不會去呼叫execute()方法。
2、第二種方式:改變表單的action的設定內容
同第一種方式,定一個login方法。只是不需要改變struts.xml檔案的內容。然後,在JSP頁面中,設定表單的action為loginMethod!login.action。這樣,Struts2也會去呼叫login方法,而不呼叫execute方法。其中,表單action="loginMethod!login.action" 中,loginMethod為struts.xml檔案中<action> 元素的name屬性值,login.action中的login為Action類中的方法名。注意:login.action的action不能少。
總結: url的格式為: (action標籤的Name屬性值)!(對應實現Aciton中的方法名)
3、第三種方式:使用萬用字元
首先同上面兩種方式,定一個login方法,然後在struts.xml檔案中配置如下內容:
<action name="*Action"
class="com.xuxinhua1984.struts2.i18n.LoginAction" method="{1}">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
清單2:struts.xml部分內容
然後在JSP頁面中,設定表單的action為loginAction,此處login為Action類中的方法名,這樣struts.xml中的*Action就可以和loginAction模糊匹配了,然後,method="{1}"就相當於method="login"。這樣一來就回到了第一種方式。
另外,這種方式甚至結果型別對應的物理檢視都可以用萬用字元。例如,如果想讓登入失敗後返回登入頁,可以設定<result name="error">/{1}.jsp</result>。這樣,此處的{1}也會被*號實際的內容替代,此處為login,所以就轉發回login.jsp頁面了。
總結:對於以上三種方式,我個人建議使用第一、第二種方式,感覺第三種方式是比較靈活,但是也容易產生混亂,且容易出錯。
Struts2支援動態方法呼叫,它指的是一個Action中有多個方法,系統根據表單元素給定的action來訪問不同的方法,而不用寫多個Action。
struts2中無需配置就可以直接呼叫Action中非execute方法的方式,就是試用struts2的動態動態方法呼叫。
動態方法呼叫(Dynamic method Invoc)是在action的名字中使用感嘆號(!)來標示要呼叫的方法名,其語法格式為
actionName!methodname.action
例如我們的配置如下:
<action name="login" class="com.pj.action.LoginAction">
<result type="json"></result>
</action>
當請求/login!query.action時,將呼叫LoginAction的query()方法,當請求/login!save.action時,將呼叫LoginAction的save()方法。
備註
Strust2提供了一種配置,用於禁用DMI,你可以在struts.xml檔案中,使用constant元素將struts.enable.DynamicMethodInvocation屬性設定為false,來關閉DMI。