因爲struts中action是用來處理和重定向的,所以在一個action中一定不止一個方法,當我們從一個前臺頁面發出請求時,有可能是向同一個action發出,但是我們想向同一個action中的非execute方法,這樣我們在struts.xml中的配置就顯得蒼白了,那麼應該怎麼辦呢?
struts中爲我們提供了兩種方法,首先是第一種,
我們在action中這樣定義:
public class helloAction {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String addUser(){
message = "addUser";
return "success";
}
public String execute(){
message = "My first struts2 demo!";
return "success";
}
}
<action name="hello" class="cn.itcast.action.helloAction" method="execute">
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
我們在想請求hello.action,但是我們返回的的是success,默認會調用execute方法,輸入
http://localhost:8080/struts_demo/test/hello
顯示
我們輸入:http://localhost:8080/struts_demo/test/hello!addUser
顯示:
這就是struts的動態調用功能,無需我們在action中進行判斷。在我們的action後面加上!funtionname------hello!addUser
這樣就可以直接調用我們的方法了。
但是這個方法在官網上的文檔上已經不推薦使用了,所以推薦大家使用第二種方法。
第二種方法:首先介紹一個常量
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
這個常量是用來定義是否支持動態調用的,當value="false"時,不允許動態調用。
使用通配符,那麼struts的配置就如下所示:
<action name="hello_*" class="cn.itcast.action.helloAction" method="{1}">
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
action 的 name的屬性值爲 hello_* ,使用*進行匹配,在method屬性值爲對第一個* 號的匹配,如果有多個* 那麼就可以進行選擇匹配,{1},代表第一個* 所匹配的內容。
http://localhost:8080/struts_demo/test/hello_execute url輸入,這樣就可以匹配execute
http://localhost:8080/struts_demo/test/hello_addUser 可以匹配addUser