struts2通配符及Action开发的三种方式

一,通配符与动态方法调用

1)准备一个UserAction.java,这个Action中有两个方法login()和register()

package com.bighuan.a_config;

import com.opensymphony.xwork2.ActionSupport;
/**
 * @author bighuan
 */
public class UserAction extends ActionSupport {

	public String login(){
		System.out.println("UserAction.login()");
		return "login";
	}
	
	public String register(){
		System.out.println("UserAction.register()");
		return "register";
	}
}
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>

	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.devMode" value="true" />
	<package name="config" namespace="/user" extends="struts-default"
		abstract="false">


		<action name="login" class="com.bighuan.a_config.UserAction"
			method="login">
			<result name="success">/login.jsp</result>
		</action>
		<action name="register" class="com.bighuan.a_config.UserAction"
			method="register">
			<result name="success">/register.jsp</result>
		</action>

	</package>

	<!-- Add packages here -->

</struts>
3)问题:访问UserAction.java中的login或者register,访问成功分别跳转到login.jsp、register.jsp.但是,如果UserAction.java中有很多个业务方法,照这样下去,岂不是要配置很多个action?答案显然不是.可以通过通配符来解决这种问题.
<!-- 使用通配符优化上面的步骤 -->
		<action name="user_*" class="com.bighuan.a_config.UserAction"
			method="{1}">
			<result name="{1}">/{1}.jsp</result>
		</action>

使用通配符访问的方式为:http://localhost:8080/struts2/user_login(struts2是web项目名,user_login表示访问UserAction中的login方法).总之就是注意方法、返回值、jsp月面命名即可,然后通过通配符匹配即可。

二,Action开发的三种方式

方式一:继承ActionSupport类,如果使用了数据校验功能,则必须继承ActionSupport。上面那个Action类就是继承了ActionSupport类。

方式二:实现Action接口,实现execute()方法/

package com.bighuan.a_config;

import com.opensymphony.xwork2.Action;
/**
 * Action开发方式2:实现Action接口
 * @author bighuan
 *
 */
public class UserAction2 implements Action {

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
方式三:既不继承ActionSupport也不实现Action接口.(ActionSupport实现了Action接口)
package com.bighuan.a_config;
/**
 * Action开发方式3:既不继承ActionSupport也不实现Action接口
 * @author bighuan
 *
 */
public class UserAction3 {

	private String userName;

	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	public String login(){
		System.out.println("UserAction3.login()"+":"+userName);
		return "success";
	}
}

不管是哪种方式,都能够进行数据的自动封装.用户访问Action,创建Action对象;创建Action对象后并不会马上执行action的业务处理方法,而是执行默认的18个拦截器(如果自己没修改的话),而默认的拦截器中就有一个参数拦截器,它会进行数据的自动封装,然后再执行业务逻辑方法.



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值