天天看點

Action的動态調用方法

Action執行的時候并不一定要執行execute方法,我們可以指定Action執行哪個方法:

1、 方法一(通過methed屬性指定執行方法):

可以在配置檔案中配置Action的時候用method=來指定執行哪個方法

<action name="userAdd" class="com.bjsxt.struts2.user.action.UserAction" method="add">

            <result>/user_add_success.jsp</result>

</action>

    這樣,隻要在action的對象中有一個add的方法,并且傳回類型為String就可以了。如果沒有method屬性,則預設執行execute()方法。

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

    public String add() {

       return SUCCESS;

    }  

}

2、 動态方法調用DMI(推薦)

可以在url位址中動态指定action執行那個方法。Url位址如下:

<a href="http://localhost:8080/Struts2_0500_ActionMethod/user/user!add">http://localhost:8080/Struts2_0500_ActionMethod/user/user!add</a>

方法:action + ! + 方法名

注:隻要Action對象中有這個方法,并且傳回類型為String就可以調用。

這樣Struts.xml配置檔案中不需要配置methed屬性。代碼如下:

&lt;action name="user" class="com.bjsxt.struts2.user.action.UserAction"&gt;

       &lt;result&gt;/user_add_success.jsp&lt;/result&gt;

Action類:

    public String add() {

    總結:推薦使用第二種動态方法調用DMI,因為第一種需要大量的Action配置,後者可以在url中動态指定執行action中哪個方法。

若轉載請注明出處!若有疑問,請回複交流!

繼續閱讀