【Struts2学习笔记(6)】Action动态方法调用
(1)在Struts1中我们使用动态方法调用的方法是使用继承DispatchAction类:
(2)在Struts2中主要有以下几种方法实现这个功能:
1.第一种:(目前已经不推荐使用)
如果Action中存在多个方法时,我们可以使用!+方法名调用指定方法。如下:
public class HelloWorldAction{
private String message;
....
public String execute() throws Exception{
this.message = "我的第一个struts2应用";
return "success";
}
public String other() throws Exception{
this.message = "第二个方法";
return "success";
}
}
假设访问上面action的URL路径为: /struts/test/helloworld.action
要访问action的other() 方法,我们可以这样调用:
/struts/test/helloworld!other.action
2.如果不想使用动态方法调用,我们可以通过常量struts.enable.DynamicMethodInvocation关闭动态方法调用。
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
3.使用通配符定义action(目前推荐使用的)
<package name="lc" namespace="/test" extends="struts-default">
<action name="helloworld_*" class="cn.itcast.action.HelloWorldAction" method="{1}"> <!-- 重点在这里 -->
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>
public class HelloWorldAction{
private String message;
....
public String execute() throws Exception{
this.message = "我的第一个struts2应用";
return "success";
}
public String other() throws Exception{
this.message = "第二个方法";
return "success";
}
}
要访问other()方法,可以通过这样的URL访问:/test/helloworld_other.action