因为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