四、动态方法调用
三、动态方法调用
action如果没在struts.xml里面配置method,则调用action时默认执行execute方法
而动态调用方法可以让一个Action处理多个请求,有三种动态调用方法
1.指定method属性
1.1在HelloWorldAction中添加函数
public String add(){
return SUCCESS;
}
1.2在struts.xml中配置,新增一个action配置
<action name="add" method="add" class="com.myz.action.HelloWorldAction">
<result>/add.jsp</result>
</action>
1.3在WebRoot目录下创建add.jsp,访问http://localhost:8080/HelloWorld/add.action即可跳转
2.感叹号方式(不推荐,因为能够通过指定url的方式访问任何一个action)
2.1在HelloWorldAction中添加函数
public String add(){
return "add";
}
2.2struts.xml中启用相关类
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
2.3配置action跳转路径
<?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>
<package name="default" namespace="/" extends="struts-default">
<action name="helloworld" class="com.myz.action.HelloWorldAction">
<result>/result.jsp</result>
<result name="add">/add.jsp</result>
</action>
</package>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
</struts>
2.4在WebRoot目录下创建add.jsp,访问http://localhost:8080/HelloWorld/helloworld!add.action即可跳转
3.通配符方式(推荐)
3.1在HelloWorldAction中添加函数
public String add(){
return "add";
}
3.2配置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>
<package name="default" namespace="/" extends="struts-default">
<!-- {1}表示的是name属性中第一个*的值,即,将来访问helloworld_add时,{1}就表示add -->
<action name="helloworld_*" method="{1}" class="com.myz.action.HelloWorldAction">
<result>/result.jsp</result>
<result name="{1}">/{1}.jsp</result>
</action>
</package>
</struts>
3.3在WebRoot目录下创建add.jsp,访问http://localhost:8080/HelloWorld/helloworld_add.action即可跳转
3.4其实一个项目中只写一个action也可以
<action name="*_*" method="{2}" class="com.myz.action.{1}Action">
<result>/result.jsp</result>
<result name="{2}">/{2}.jsp</result>
</action>

浙公网安备 33010602011771号