动态调用方法

        若 Action 中存在多个方法,但在配置文件中注册该 Action 时,并未为每个方法指定一个<action/>,而是只为这一个 Action 类注册了一个<action/>。那么,当用户访问该<action/>的时,到底执行哪个方法,则是由用户发出的请求动态决定。即仅从配置文件是看不出<action/>标签是对应哪个方法的,只有在运行时根据具体的用户请求,才可决定执行哪个方法。这种情况称为动态调用方法。动态调用方法有两种实现方式。

动态方法调用

        动态方法调用是指,在地址栏提交请求时,直接在 URL 后跟上“!方法名”方式动态指定要执行的方法

        不过,动态方法调用默认是关闭的,可以通过改变“动态方法调用”常量struts.enable.DynamicMethodInvocation的值来开启动态方法调用功能。

        可以在struts.xml中设置struts.enable.DynamicMethodInvocation = true;

方法如下,在struts节点下加下面这句。

<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
示例:

Action代码示例:

package cn.ccnu.actions;

public class SomeAction {
	public String doFirst(){
		return "first";
	}
	
	public String doSecond(){
		return "second";
	}
}
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>
	<constant name="struts.enable.DynamicMethodInvocation " value="true"/>
    <package name="default" namespace="/" extends="struts-default">
        <action name="some" class="cn.ccnu.actions.SomeAction">
        	<result name="first">/first.jsp</result>
        	<result name="second">/second.jsp</result>
        </action>
    </package>
</struts>
地址栏访问

http://localhost:8080/02_dynamicmethodinvocation/some!doFirst.action

二使用通配符定义的 Action

        使用通配符定义的 action 是指,在配置文件中定义 action 时,其 name 中包含通配符*。请求 URL 中提交的 action的具体值,将作为*的真实值。而<action/>中的占位符(占位符,从1开始计数)将接收这个真实值。占位符一般出现在 method 属性中。

示例:

Action代码示例如上。

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">
        <action name="some_*" class="cn.ccnu.actions.SomeAction" method="{1}">
        	<result name="first">/first.jsp</result>
        	<result name="second">/second.jsp</result>
        </action>
    </package>
</struts>

地址栏访问

http://localhost:8080/02_dynamicmethodinvocation/some_doFirst.action

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值