struts2学习(9)——动态方法调用和通配符

本文介绍了在Struts2框架中如何实现动态方法调用功能。通过两种配置方式,可以使一个Action支持多个方法调用,提高代码复用性和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值