Struts2動態方法調用
在Struts2中方法調用概括起來主要有三種形式
指定method屬性
<action name="student" class="com.itmyhome.Student" method="add">
<result name="add">/success.jsp</result>
</action>
這樣Struts2就會調用Student 中的add方法。
動態方法調用(DMI)
用這種方法需要設置一個常量
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
動態方法調用是指表單元素的action并不是直接等于某個Action的名字,而是以如下形式來指定Form的action屬性
<!-- action屬性為action!methodName的形式 -->
<action = "action!methodName.action"
在struts.xml中定義如下Action
<action name="student" class="com.itmyhome.StudentAction">
<result name="add">/add.jsp</result>
<result name="delete">/delete.jsp</result>
</action>
StudentAction代碼為
public class StudentAction extends ActionSupport {
public String add(){
return "add";
}
public String delete(){
return "delete";
}
}
則在JSP中用如下方式調用方法
<a href=”http://student!add.action“> 新增學生</a>
<a href=“http://student!delete.action”> 刪除學生</a>
通配符(推薦使用)
<action name="student*" class="com.itmyhome.StudentAction" method="{1}">
<result name="{1}">/student{1}.jsp</result>
</action>
則在JSP中用如下方式調用方法
<a href=“http://studentadd”> 新增學生</a>
<a href=“http://studentdelete”> 刪除學生</a>
studentadd就會調用StudentAction中的add方法 然后跳轉到studentadd.jsp
studentdelete就會調用StudentAction中的delete方法 然后跳轉到studentdelete.jsp
Struts2支持動態方法調用,它指的是一個Action中有多個方法, 系統根據表單元素給定的action來訪問不同的方法,而不用寫多個Action。