Struts2中的動態方法調用
一、動態方法調用介紹
在Struts2開發中,默認執行的是execute方法,有時候我們會在一個Action中寫多個方法,這時候我們需要在請求中調用我們想調用的方法,而不是採用多寫Action的方式。
使用動態方法可以避免Action太多。
二、動態方法調用常見方法
本示例中的Action類代碼如下所示:
package blog.wlb.net.oschina.my;
public class SimpleAction {
public String test1(){
System.out.println("執行測試方法1");
return "test1";
}
public String test2(){
System.out.println("執行測試方法2");
return "test2";
}
public String test3(){
System.out.println("執行測試方法3");
return "test3";
}
public String test4(){
System.out.println("執行測試方法4");
return "test4";
}
}
本示例中的struts.xml中的代碼如下所示:
<?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.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="simple" class="blog.wlb.net.oschina.my.SimpleAction">
<result name="test1">/test1.jsp</result>
<result name="test2">/test2.jsp</result>
<result name="test3">/test3.jsp</result>
</action>
</package>
</struts>
(1)指定method方法
Get地址請求形如:http://localhost:8080/web/simple.action?method:test1
Post請求代碼如下所示:
<form action="web/simple.action" method="post">
<input type="hidden" name="method:test1" />
<input type="submit" value="提交" />
</form>
(2)歎號方式調用
形如:http://localhost:8080/web/simple!test1.action
注意:這種方式官方不推薦。
(3)通配符方式
修改struts.xml中代碼
<action name="simple_*" class="blog.wlb.net.oschina.my.SimpleAction" method="{1}">
<result name="test1">/test1.jsp</result>
<result name="test2">/test2.jsp</result>
<result name="test3">/test3.jsp</result>
</action>
具體訪問爲
http://localhost:8080/web/simple_test1
http://localhost:8080/web/simple_test2
http://localhost:8080/web/simple_test3
http://localhost:8080/web/simple_test4
這種的意思是所有請求的爲simple_開頭的action都會根據下劃線後面的參數動態的匹配action中的方法。
這種方式是官方推薦的方式。
三、知識擴展
(1)如何啓用或禁用動態方法調用
動態方法調用默認是啓用的,如果想禁用,可以在struts.xml中設置如下代碼:
<constant name="struts.enable.DynamicMethodInvocation" value="false" />