当在一个service有不同的调用方法,但是由于action的默认方法为execute()。在Struts中可以使用三种方式进行处理。
通过URL叹号“!”参数
新建service类,其中有两个方法show()方法和deal()方法,分别在其中输出一句话:
package com.struts.service;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
/**
* @TODO TODO
* @author Administrator
* @date 2015年7月7日 下午4:20:11
* @version 1.0
*/
@SuppressWarnings("serial")
public class ActionMethodService extends ActionSupport{
public String deal(){
System.out.println("deal()方法调用");
return Action.SUCCESS;
}
public String show(){
System.out.println("show()方法调用");
return Action.SUCCESS;
}
}
struts配置文件如下:
<action name="method" class="com.struts.service.ActionMethodService">
<result name="success">/method.jsp</result>
</action>
访问show方法:http://localhost:8080/struts/method!show.action
访问deal方法:http://localhost:8080/struts/method!deal.action
在action标记中加入method属性
在配置文件中的action标记中加入method属性,指定调用class类中的指定方法,如下配置:
<action name="method_show" class="com.struts.service.ActionMethodService" method="show">
<result name="success">/method.jsp</result>
</action>
<action name="method_deal" class="com.struts.service.ActionMethodService" method="deal">
<result name="success">/method.jsp</result>
</action>
调用deal方法:http://localhost:8080/struts/method_deal.action
调用show方法:http://localhost:8080/struts/method_show.action
缺点:当一个class中有多个处理方法时,需要在配置文件中针对同一个类配置多个action,比较繁琐。下面的动态方法调用避免了此点,可以根据访问的url来动态调用不同的方法。
动态方法调用
struts2默认不允许动态方法调用,因此需要配置常量
<!-- 动态方法调用 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
配置action如下:
<!-- 动态方法调用 -->
<action name="method*" class="com.struts.service.ActionMethodService" method="{1}">
<result name="success">/method.jsp</result>
</action>
调用deal方法:http://localhost:8080/struts/methoddeal.action
调用show方法:http://localhost:8080/struts/methodshow.action
优点:可以根据请求的url来动态匹配从而调用不同的方法。